CCMain.m 253 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714
  1. //
  2. // CCMain.m
  3. // Crypto Cloud Technology Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCMain.h"
  24. #import "AppDelegate.h"
  25. #import "CCPhotos.h"
  26. #import "CCSynchronize.h"
  27. #import "CCTransfersCell.h"
  28. #import "OCActivity.h"
  29. #import "OCNotifications.h"
  30. #import "OCNotificationsAction.h"
  31. #import "OCFrameworkConstants.h"
  32. #import "OCCapabilities.h"
  33. #import "CTAssetCheckmark.h"
  34. #import "NCAutoUpload.h"
  35. #import "NCBridgeSwift.h"
  36. @interface CCMain () <CCActionsDeleteDelegate, CCActionsRenameDelegate, CCActionsSearchDelegate, CCActionsDownloadThumbnailDelegate, CCActionsSettingFavoriteDelegate>
  37. {
  38. tableMetadata *_metadata;
  39. BOOL _isRoot;
  40. BOOL _isViewDidLoad;
  41. BOOL _isOfflineServerUrl;
  42. BOOL _isPickerCriptate; // if is cryptated image or video back from picker
  43. BOOL _isSelectedMode;
  44. NSMutableArray *_selectedMetadatas;
  45. NSMutableArray *_queueSelector;
  46. NSUInteger _numSelectedMetadatas;
  47. UIImageView *_ImageTitleHomeCryptoCloud;
  48. UIView *_reMenuBackgroundView;
  49. UITapGestureRecognizer *_singleFingerTap;
  50. NSString *_directoryGroupBy;
  51. NSString *_directoryOrder;
  52. NSUInteger _failedAttempts;
  53. NSDate *_lockUntilDate;
  54. NSString *_fatherPermission;
  55. UIRefreshControl *_refreshControl;
  56. UIDocumentInteractionController *_docController;
  57. CCHud *_hud;
  58. CCHud *_hudDeterminate;
  59. // Datasource
  60. CCSectionDataSourceMetadata *_sectionDataSource;
  61. NSDate *_dateReadDataSource;
  62. // Search
  63. BOOL _isSearchMode;
  64. NSString *_searchFileName;
  65. NSMutableArray *_searchResultMetadatas;
  66. NSString *_depth;
  67. NSString *_noFilesSearchTitle;
  68. NSString *_noFilesSearchDescription;
  69. NSTimer *_timerWaitInput;
  70. // Login
  71. CCLoginWeb *_loginWeb;
  72. CCLogin *_loginVC;
  73. }
  74. @end
  75. @implementation CCMain
  76. #pragma --------------------------------------------------------------------------------------------
  77. #pragma mark ===== Init =====
  78. #pragma --------------------------------------------------------------------------------------------
  79. - (id)initWithCoder:(NSCoder *)aDecoder
  80. {
  81. if (self = [super initWithCoder:aDecoder]) {
  82. _directoryOrder = [CCUtility getOrderSettings];
  83. _directoryGroupBy = [CCUtility getGroupBySettings];
  84. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:@"initializeMain" object:nil];
  85. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:@"clearDateReadDataSource" object:nil];
  86. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:@"setTitleMain" object:nil];
  87. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  88. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  89. }
  90. return self;
  91. }
  92. #pragma --------------------------------------------------------------------------------------------
  93. #pragma mark ===== View =====
  94. #pragma --------------------------------------------------------------------------------------------
  95. - (void)viewDidLoad
  96. {
  97. [super viewDidLoad];
  98. // init object
  99. _metadata = [tableMetadata new];
  100. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  101. _hudDeterminate = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  102. _selectedMetadatas = [NSMutableArray new];
  103. _queueSelector = [NSMutableArray new];
  104. _sectionDataSource = [CCSectionDataSourceMetadata new];
  105. _isViewDidLoad = YES;
  106. _fatherPermission = @"";
  107. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  108. _searchResultMetadatas = [NSMutableArray new];
  109. _searchFileName = @"";
  110. _depth = @"0";
  111. _noFilesSearchTitle = @"";
  112. _noFilesSearchDescription = @"";
  113. // delegate
  114. self.tableView.delegate = self;
  115. self.tableView.tableFooterView = [UIView new];
  116. self.tableView.separatorColor = [NCBrandColor sharedInstance].seperator;
  117. self.tableView.emptyDataSetDelegate = self;
  118. self.tableView.emptyDataSetSource = self;
  119. self.searchController.delegate = self;
  120. self.searchController.searchBar.delegate = self;
  121. [[CCNetworking sharedNetworking] settingDelegate:self];
  122. // Custom Cell
  123. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  124. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  125. // long press recognizer TableView
  126. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  127. [self.tableView addGestureRecognizer:longPressRecognizer];
  128. // Pull-to-Refresh
  129. [self createRefreshControl];
  130. // Register for 3D Touch Previewing if available
  131. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable))
  132. {
  133. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  134. }
  135. // Back Button
  136. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]])
  137. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"] style:UIBarButtonItemStylePlain target:nil action:nil];
  138. // reMenu Background
  139. _reMenuBackgroundView = [[UIView alloc] init];
  140. _reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  141. // if this is not Main (the Main uses inizializeMain)
  142. if (_isRoot == NO && app.activeAccount.length > 0) {
  143. // Settings this folder & delegate & Loading datasource
  144. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  145. // Load Datasource
  146. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  147. // Read Folder
  148. [self readFolderWithForced:NO serverUrl:_serverUrl];
  149. }
  150. // Title
  151. [self setTitle];
  152. // Search
  153. self.definesPresentationContext = YES;
  154. self.searchController.searchResultsUpdater = self;
  155. self.searchController.dimsBackgroundDuringPresentation = NO;
  156. self.tableView.tableHeaderView = self.searchController.searchBar;
  157. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].seperator;
  158. [self.searchController.searchBar sizeToFit];
  159. self.searchController.searchBar.delegate = self;
  160. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_this_folder_",nil);
  161. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12) {
  162. if (_isRoot)
  163. self.searchController.searchBar.scopeButtonTitles = [NSArray arrayWithObjects:NSLocalizedString(@"_search_this_folder_",nil),NSLocalizedString(@"_search_all_folders_",nil), nil];
  164. else
  165. self.searchController.searchBar.scopeButtonTitles = [NSArray arrayWithObjects:NSLocalizedString(@"_search_this_folder_",nil),NSLocalizedString(@"_search_sub_folder_",nil), nil];
  166. } else {
  167. self.searchController.searchBar.scopeButtonTitles = nil;
  168. }
  169. // Hide Search Filed on Load
  170. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  171. }
  172. // Apparirà
  173. - (void)viewWillAppear:(BOOL)animated
  174. {
  175. [super viewWillAppear:animated];
  176. // test
  177. if (app.activeAccount.length == 0)
  178. return;
  179. // Settings this folder & delegate & Loading datasource
  180. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  181. [[CCNetworking sharedNetworking] settingDelegate:self];
  182. // Color
  183. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  184. [app aspectTabBar:self.tabBarController.tabBar hidden:NO];
  185. if (_isSelectedMode)
  186. [self setUINavigationBarSelected];
  187. else
  188. [self setUINavigationBarDefault];
  189. // Plus Button
  190. [app plusButtonVisibile:true];
  191. }
  192. // E' arrivato
  193. - (void)viewDidAppear:(BOOL)animated
  194. {
  195. [super viewDidAppear:animated];
  196. // Active Main
  197. app.activeMain = self;
  198. // Test viewDidLoad
  199. if (_isViewDidLoad) {
  200. _isViewDidLoad = NO;
  201. } else {
  202. if (app.activeAccount.length > 0) {
  203. // Load Datasource
  204. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  205. // Read Folder
  206. [self readFolderWithForced:NO serverUrl:_serverUrl];
  207. }
  208. }
  209. // Title
  210. [self setTitle];
  211. }
  212. - (void)viewWillDisappear:(BOOL)animated
  213. {
  214. [super viewWillDisappear:animated];
  215. [self closeAllMenu];
  216. }
  217. - (void)didReceiveMemoryWarning
  218. {
  219. [super didReceiveMemoryWarning];
  220. // Dispose of any resources that can be recreated.
  221. }
  222. - (BOOL)prefersStatusBarHidden
  223. {
  224. return NO;
  225. }
  226. // detect scroll for remove keyboard in search mode
  227. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  228. {
  229. if (_isSearchMode && scrollView == self.tableView) {
  230. [self.searchController.searchBar endEditing:YES];
  231. }
  232. }
  233. - (void)changeTheming
  234. {
  235. if (self.isViewLoaded && self.view.window)
  236. [app changeTheming:self];
  237. // Refresh control
  238. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  239. // Reload Table View
  240. [self tableViewReload];
  241. }
  242. #pragma --------------------------------------------------------------------------------------------
  243. #pragma mark ===== Initizlize Mail =====
  244. #pragma --------------------------------------------------------------------------------------------
  245. - (void)initializeMain:(NSNotification *)notification
  246. {
  247. _directoryGroupBy = nil;
  248. _directoryOrder = nil;
  249. _dateReadDataSource = nil;
  250. // test
  251. if (app.activeAccount.length == 0)
  252. return;
  253. if ([app.listMainVC count] == 0 || _isRoot) {
  254. // This is Root
  255. _isRoot = YES;
  256. // Crypto Mode
  257. if ([[CCUtility getKeyChainPasscodeForUUID:[CCUtility getUUID]] length] == 0) {
  258. app.isCryptoCloudMode = NO;
  259. } else {
  260. app.isCryptoCloudMode = YES;
  261. }
  262. // go Home
  263. [self.navigationController popToRootViewControllerAnimated:NO];
  264. // Remove search mode
  265. [self cancelSearchBar];
  266. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  267. _isFolderEncrypted = NO;
  268. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  269. // add list
  270. [app.listMainVC setObject:self forKey:_serverUrl];
  271. // setting Networking
  272. [[CCNetworking sharedNetworking] settingDelegate:self];
  273. [[CCNetworking sharedNetworking] settingAccount];
  274. // populate shared Link & User variable
  275. NSArray *results = [[NCManageDatabase sharedInstance] getShares];
  276. if (results) {
  277. app.sharesLink = results[0];
  278. app.sharesUserAndGroup = results[1];
  279. }
  280. // Setting Theming
  281. [app settingThemingColorBrand];
  282. // Load Datasource
  283. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  284. // Load Folder
  285. [self readFolderWithForced:NO serverUrl:_serverUrl];
  286. // Load photo datasorce
  287. if (app.activePhotos)
  288. [app.activePhotos reloadDatasourceForced];
  289. // remove all of detail
  290. if (app.activeDetail)
  291. [app.activeDetail removeAllView];
  292. // remove all Notification Messages
  293. [app.listOfNotifications removeAllObjects];
  294. // home main
  295. app.homeMain = self;
  296. // Initializations
  297. [app applicationInitialized];
  298. } else {
  299. // reload datasource
  300. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  301. }
  302. }
  303. #pragma --------------------------------------------------------------------------------------------
  304. #pragma mark ==== DZNEmptyDataSetSource ====
  305. #pragma --------------------------------------------------------------------------------------------
  306. /*
  307. - (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView
  308. {
  309. if(_isSearchMode)
  310. return NO;
  311. else
  312. return YES;
  313. }
  314. */
  315. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  316. {
  317. return YES;
  318. }
  319. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  320. {
  321. return [UIColor whiteColor];
  322. }
  323. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  324. {
  325. if (_isSearchMode)
  326. return [UIImage imageNamed:@"searchBig"];
  327. else
  328. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"filesNoFiles"] color:[NCBrandColor sharedInstance].brand];
  329. }
  330. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  331. {
  332. NSString *text;
  333. if (_isSearchMode)
  334. text = _noFilesSearchTitle;
  335. else
  336. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  337. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  338. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  339. }
  340. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  341. {
  342. NSString *text;
  343. if (_isSearchMode)
  344. text = _noFilesSearchDescription;
  345. else
  346. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  347. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  348. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  349. paragraph.alignment = NSTextAlignmentCenter;
  350. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  351. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  352. }
  353. #pragma --------------------------------------------------------------------------------------------
  354. #pragma mark ===== minChar Text Field DidChange =====
  355. #pragma --------------------------------------------------------------------------------------------
  356. - (void)minCharTextFieldDidChange:(UITextField *)sender
  357. {
  358. UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
  359. if (alertController)
  360. {
  361. UITextField *fileName = alertController.textFields.firstObject;
  362. UIAlertAction *okAction = alertController.actions.lastObject;
  363. okAction.enabled = fileName.text.length > 0;
  364. }
  365. }
  366. #pragma --------------------------------------------------------------------------------------------
  367. #pragma mark ===== Graphic Window =====
  368. #pragma --------------------------------------------------------------------------------------------
  369. - (void)createRefreshControl
  370. {
  371. _refreshControl = [UIRefreshControl new];
  372. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  373. _refreshControl.backgroundColor = [UIColor colorWithRed:235.0/255.0 green:235.0/255.0 blue:235.0/255.0 alpha:1.0];
  374. [_refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  375. [self setRefreshControl:_refreshControl];
  376. }
  377. - (void)deleteRefreshControl
  378. {
  379. [_refreshControl endRefreshing];
  380. self.refreshControl = nil;
  381. }
  382. - (void)refreshControlTarget
  383. {
  384. [self readFolderWithForced:YES serverUrl:_serverUrl];
  385. // Actuate `Peek` feedback (weak boom)
  386. AudioServicesPlaySystemSound(1519);
  387. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  388. }
  389. - (void)setTitle
  390. {
  391. // Color text self.navigationItem.title
  392. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  393. if (_isSelectedMode) {
  394. NSUInteger totali = [_sectionDataSource.allRecordsDataSource count];
  395. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  396. self.navigationItem.titleView = nil;
  397. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  398. } else {
  399. // we are in home : LOGO BRAND
  400. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]]) {
  401. self.navigationItem.title = nil;
  402. if ([app.reachability isReachable] == NO)
  403. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogoOffline"]];
  404. else
  405. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"]];
  406. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  407. UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuLogo)];
  408. [singleTap setNumberOfTapsRequired:1];
  409. [_ImageTitleHomeCryptoCloud addGestureRecognizer:singleTap];
  410. self.navigationItem.titleView = _ImageTitleHomeCryptoCloud;
  411. } else {
  412. self.navigationItem.title = _titleMain;
  413. }
  414. }
  415. }
  416. - (void)setUINavigationBarDefault
  417. {
  418. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  419. UIBarButtonItem *buttonMore, *buttonNotification;
  420. // =
  421. buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationControllerMenu"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleReMainMenu)];
  422. buttonMore.enabled = true;
  423. // <
  424. self.navigationController.navigationBar.hidden = NO;
  425. // Notification
  426. if ([app.listOfNotifications count] > 0) {
  427. buttonNotification = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"notification"] style:UIBarButtonItemStylePlain target:self action:@selector(viewNotification)];
  428. buttonNotification.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  429. buttonNotification.enabled = true;
  430. }
  431. if (buttonNotification)
  432. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, buttonNotification, nil];
  433. else
  434. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  435. self.navigationItem.leftBarButtonItem = nil;
  436. }
  437. - (void)setUINavigationBarSelected
  438. {
  439. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  440. UIImage *icon = [UIImage imageNamed:@"navigationControllerMenu"];
  441. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  442. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  443. self.navigationItem.leftBarButtonItem = leftButton;
  444. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  445. }
  446. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  447. {
  448. [self closeAllMenu];
  449. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  450. }];
  451. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  452. }
  453. - (void)cancelSelect
  454. {
  455. [self tableViewSelect:NO];
  456. [app.reSelectMenu close];
  457. }
  458. - (void)closeAllMenu
  459. {
  460. // close Menu
  461. [app.reSelectMenu close];
  462. [app.reMainMenu close];
  463. // Close Menu Logo
  464. [CCMenuAccount dismissMenu];
  465. }
  466. #pragma --------------------------------------------------------------------------------------------
  467. #pragma mark ===== Document Picker =====
  468. #pragma --------------------------------------------------------------------------------------------
  469. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  470. {
  471. NSLog(@"Cancelled");
  472. }
  473. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  474. {
  475. NSLog(@"Cancelled");
  476. }
  477. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  478. {
  479. documentPicker.delegate = self;
  480. [self presentViewController:documentPicker animated:YES completion:nil];
  481. }
  482. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  483. {
  484. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  485. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  486. __block NSError *error;
  487. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  488. NSString *fileName = [url lastPathComponent];
  489. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileName];
  490. NSData *data = [NSData dataWithContentsOfURL:newURL];
  491. if (data && error == nil) {
  492. if ([data writeToFile:fileNamePath options:NSDataWritingAtomic error:&error]) {
  493. // Upload File
  494. [[CCNetworking sharedNetworking] uploadFile:fileName serverUrl:_serverUrl cryptated:_isPickerCriptate onlyPlist:NO session:k_upload_session taskStatus: k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  495. } else {
  496. [app messageNotification:@"_error_" description:error.description visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  497. }
  498. } else {
  499. [app messageNotification:@"_error_" description:@"_read_file_error_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  500. }
  501. }];
  502. }
  503. }
  504. - (void)openImportDocumentPicker
  505. {
  506. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  507. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  508. documentProviderMenu.popoverPresentationController.sourceView = self.view;
  509. documentProviderMenu.popoverPresentationController.sourceRect = self.view.bounds;
  510. documentProviderMenu.delegate = self;
  511. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  512. }
  513. #pragma --------------------------------------------------------------------------------------------
  514. #pragma mark ===== Assets Picker =====
  515. #pragma --------------------------------------------------------------------------------------------
  516. - (void)openAssetsPickerController
  517. {
  518. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  519. checkmark.tintColor = [NCBrandColor sharedInstance].brand;
  520. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeTop];
  521. UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedIn:[CTAssetsPickerController class], nil];
  522. [app aspectNavigationControllerBar:navBar encrypted:NO online:YES hidden:NO];
  523. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
  524. dispatch_async(dispatch_get_main_queue(), ^{
  525. // init picker
  526. CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
  527. // set delegate
  528. picker.delegate = self;
  529. // to show selection order
  530. //picker.showsSelectionIndex = YES;
  531. // to present picker as a form sheet in iPad
  532. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  533. picker.modalPresentationStyle = UIModalPresentationFormSheet;
  534. // present picker
  535. [self presentViewController:picker animated:YES completion:nil];
  536. });
  537. }];
  538. }
  539. - (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSMutableArray *)assets
  540. {
  541. [picker dismissViewControllerAnimated:YES completion:^{
  542. CreateFormUploadAssets *form = [[CreateFormUploadAssets alloc] init:_titleMain serverUrl:_serverUrl assets:assets cryptated:_isPickerCriptate session:k_upload_session];
  543. form.title = NSLocalizedString(@"_upload_photos_videos_", nil);
  544. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  545. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  546. [self presentViewController:navigationController animated:YES completion:nil];
  547. }];
  548. }
  549. #pragma --------------------------------------------------------------------------------------------
  550. #pragma mark ===== UIDocumentInteractionControllerDelegate =====
  551. #pragma --------------------------------------------------------------------------------------------
  552. - (void)documentInteractionControllerDidDismissOptionsMenu:(UIDocumentInteractionController *)controller
  553. {
  554. // evitiamo il rimando della eventuale photo e/o video
  555. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  556. if (tableAccount.autoUpload) {
  557. [[NCManageDatabase sharedInstance] setAccountAutoUploadDateAssetType:PHAssetMediaTypeImage assetDate:[NSDate date]];
  558. [[NCManageDatabase sharedInstance] setAccountAutoUploadDateAssetType:PHAssetMediaTypeVideo assetDate:[NSDate date]];
  559. }
  560. }
  561. /*
  562. #pragma --------------------------------------------------------------------------------------------
  563. #pragma mark ===== UnZipFile =====
  564. #pragma --------------------------------------------------------------------------------------------
  565. - (void)unZipFile:(NSString *)fileID
  566. {
  567. [_hudDeterminate visibleHudTitle:NSLocalizedString(@"_unzip_in_progress_", nil) mode:MBProgressHUDModeDeterminate color:nil];
  568. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  569. NSString *fileZip = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID];
  570. [SSZipArchive unzipFileAtPath:fileZip toDestination:[CCUtility getDirectoryLocal] overwrite:YES password:nil progressHandler:^(NSString *entry, unz_file_info zipInfo, long entryNumber, long total) {
  571. dispatch_async(dispatch_get_main_queue(), ^{
  572. float progress = (float) entryNumber / (float)total;
  573. [_hudDeterminate progress:progress];
  574. });
  575. } completionHandler:^(NSString *path, BOOL succeeded, NSError *error) {
  576. dispatch_async(dispatch_get_main_queue(), ^{
  577. [_hudDeterminate hideHud];
  578. if (succeeded) [app messageNotification:@"_info_" description:@"_file_unpacked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  579. else [app messageNotification:@"_error_" description:[NSString stringWithFormat:@"Error %ld", (long)error.code] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  580. });
  581. }];
  582. });
  583. }
  584. */
  585. #pragma --------------------------------------------------------------------------------------------
  586. #pragma mark ===== Create New (OpenModel) =====
  587. #pragma --------------------------------------------------------------------------------------------
  588. - (void)openModel:(NSString *)tipo isNew:(BOOL)isnew
  589. {
  590. UIViewController *viewController;
  591. NSString *fileName, *uuid, *fileID, *serverUrl;
  592. NSIndexPath * index = [self.tableView indexPathForSelectedRow];
  593. [self.tableView deselectRowAtIndexPath:index animated:NO];
  594. if (isnew) {
  595. fileName = nil;
  596. uuid = [CCUtility getUUID];
  597. fileID = nil;
  598. serverUrl = _serverUrl;
  599. } else {
  600. fileName = _metadata.fileName;
  601. uuid = _metadata.uuid;
  602. fileID = _metadata.fileID;
  603. serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  604. }
  605. if ([tipo isEqualToString:@"cartadicredito"])
  606. viewController = [[CCCartaDiCredito alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  607. if ([tipo isEqualToString:@"bancomat"])
  608. viewController = [[CCBancomat alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  609. if ([tipo isEqualToString:@"contocorrente"])
  610. viewController = [[CCContoCorrente alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  611. if ([tipo isEqualToString:@"accountweb"])
  612. viewController = [[CCAccountWeb alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  613. if ([tipo isEqualToString:@"patenteguida"])
  614. viewController = [[CCPatenteGuida alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  615. if ([tipo isEqualToString:@"cartaidentita"])
  616. viewController = [[CCCartaIdentita alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  617. if ([tipo isEqualToString:@"passaporto"])
  618. viewController = [[CCPassaporto alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  619. if ([tipo isEqualToString:@"note"]) {
  620. viewController = [[CCNote alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  621. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  622. [self presentViewController:navigationController animated:YES completion:nil];
  623. } else {
  624. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  625. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  626. [self presentViewController:navigationController animated:YES completion:nil];
  627. }
  628. }
  629. // New folder or new photo or video
  630. - (void)returnCreate:(NSInteger)type
  631. {
  632. switch (type) {
  633. /* PLAIN */
  634. case k_returnCreateFolderPlain: {
  635. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  636. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  637. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  638. }];
  639. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  640. NSLog(@"Cancel action");
  641. }];
  642. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  643. UITextField *fileName = alertController.textFields.firstObject;
  644. [self createFolder:fileName.text autoUploadDirectory:NO];
  645. }];
  646. okAction.enabled = NO;
  647. [alertController addAction:cancelAction];
  648. [alertController addAction:okAction];
  649. [self presentViewController:alertController animated:YES completion:nil];
  650. }
  651. break;
  652. case k_returnCreateFotoVideoPlain: {
  653. _isPickerCriptate = false;
  654. [self openAssetsPickerController];
  655. }
  656. break;
  657. case k_returnCreateFilePlain: {
  658. _isPickerCriptate = false;
  659. [self openImportDocumentPicker];
  660. }
  661. break;
  662. /* ENCRYPTED */
  663. case k_returnCreateFolderEncrypted: {
  664. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  665. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  666. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  667. }];
  668. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  669. NSLog(@"Cancel action");
  670. }];
  671. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  672. UITextField *fileName = alertController.textFields.firstObject;
  673. [self createFolderEncrypted:fileName.text];
  674. }];
  675. okAction.enabled = NO;
  676. [alertController addAction:cancelAction];
  677. [alertController addAction:okAction];
  678. [self presentViewController:alertController animated:YES completion:nil];
  679. }
  680. break;
  681. case k_returnCreateFotoVideoEncrypted: {
  682. _isPickerCriptate = true;
  683. [self openAssetsPickerController];
  684. }
  685. break;
  686. case k_returnCreateFileEncrypted: {
  687. _isPickerCriptate = true;
  688. [self openImportDocumentPicker];
  689. }
  690. break;
  691. /* UTILITY */
  692. case k_returnNote:
  693. [self openModel:@"note" isNew:true];
  694. break;
  695. case k_returnAccountWeb:
  696. [self openModel:@"accountweb" isNew:true];
  697. break;
  698. /* BANK */
  699. case k_returnCartaDiCredito:
  700. [self openModel:@"cartadicredito" isNew:true];
  701. break;
  702. case k_returnBancomat:
  703. [self openModel:@"bancomat" isNew:true];
  704. break;
  705. case k_returnContoCorrente:
  706. [self openModel:@"contocorrente" isNew:true];
  707. break;
  708. /* DOCUMENT */
  709. case k_returnPatenteGuida:
  710. [self openModel:@"patenteguida" isNew:true];
  711. break;
  712. case k_returnCartaIdentita:
  713. [self openModel:@"cartaidentita" isNew:true];
  714. break;
  715. case k_returnPassaporto:
  716. [self openModel:@"passaporto" isNew:true];
  717. break;
  718. }
  719. }
  720. #pragma --------------------------------------------------------------------------------------------
  721. #pragma mark ===== Save selected File =====
  722. #pragma --------------------------------------------------------------------------------------------
  723. -(void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  724. {
  725. if (error)
  726. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  727. else
  728. [app messageNotification:@"_save_selected_files_" description:@"_file_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:error.code];
  729. }
  730. - (void)saveSelectedFiles
  731. {
  732. NSLog(@"[LOG] Start download selected files ...");
  733. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  734. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  735. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  736. for (tableMetadata *metadata in metadatas) {
  737. if (metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_file] && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  738. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  739. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorSave selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  740. }
  741. }
  742. [_hud hideHud];
  743. });
  744. [self tableViewSelect:NO];
  745. }
  746. #pragma --------------------------------------------------------------------------------------------
  747. #pragma mark ===== Change Password =====
  748. #pragma --------------------------------------------------------------------------------------------
  749. - (void) loginSuccess:(NSInteger)loginType
  750. {
  751. [self readFolderWithForced:YES serverUrl:_serverUrl];
  752. }
  753. - (void)changePasswordAccount
  754. {
  755. // Brand
  756. if ([NCBrandOptions sharedInstance].use_login_web) {
  757. _loginWeb = [CCLoginWeb new];
  758. _loginWeb.delegate = self;
  759. _loginWeb.loginType = loginModifyPasswordUser;
  760. dispatch_async(dispatch_get_main_queue(), ^ {
  761. [_loginWeb presentModalWithDefaultTheme:self];
  762. });
  763. } else {
  764. _loginVC = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  765. _loginVC.delegate = self;
  766. _loginVC.loginType = loginModifyPasswordUser;
  767. [self presentViewController:_loginVC animated:YES completion:nil];
  768. }
  769. }
  770. #pragma mark -
  771. #pragma --------------------------------------------------------------------------------------------
  772. #pragma mark ===== Peek & Pop =====
  773. #pragma --------------------------------------------------------------------------------------------
  774. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  775. {
  776. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  777. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  778. if (metadata.thumbnailExists && !metadata.cryptated) {
  779. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  780. if (cell) {
  781. previewingContext.sourceRect = cell.frame;
  782. CCPeekPop *vc = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  783. vc.delegate = self;
  784. vc.metadata = metadata;
  785. return vc;
  786. }
  787. }
  788. return nil;
  789. }
  790. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  791. {
  792. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  793. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  794. }
  795. #pragma mark -
  796. #pragma --------------------------------------------------------------------------------------------
  797. #pragma mark ==== External Sites ====
  798. #pragma --------------------------------------------------------------------------------------------
  799. - (void)getExternalSitesServerSuccess:(NSArray *)listOfExternalSites
  800. {
  801. [[NCManageDatabase sharedInstance] deleteExternalSites];
  802. for (OCExternalSites *tableExternalSites in listOfExternalSites)
  803. [[NCManageDatabase sharedInstance] addExternalSites:tableExternalSites];
  804. }
  805. - (void)getExternalSitesServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  806. {
  807. NSLog(@"[LOG] No External Sites found");
  808. }
  809. #pragma --------------------------------------------------------------------------------------------
  810. #pragma mark ==== Activity ====
  811. #pragma --------------------------------------------------------------------------------------------
  812. - (void)getActivityServerSuccess:(NSArray *)listOfActivity
  813. {
  814. [[NCManageDatabase sharedInstance] addActivityServer:listOfActivity];
  815. // Reload Activity Data Source
  816. [app.activeActivity reloadDatasource];
  817. }
  818. - (void)getActivityServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  819. {
  820. NSLog(@"[LOG] No Activity found");
  821. }
  822. #pragma --------------------------------------------------------------------------------------------
  823. #pragma mark ==== Notification ====
  824. #pragma --------------------------------------------------------------------------------------------
  825. - (void)getNotificationServerSuccess:(NSArray *)listOfNotifications
  826. {
  827. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  828. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  829. // Order by date
  830. NSArray *sortedListOfNotifications = [listOfNotifications sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  831. OCNotifications *notification1 = obj1, *notification2 = obj2;
  832. return [notification2.date compare: notification1.date];
  833. }];
  834. // verify if listOfNotifications is changed
  835. NSString *old = @"", *new = @"";
  836. for (OCNotifications *notification in listOfNotifications)
  837. new = [new stringByAppendingString:@(notification.idNotification).stringValue];
  838. for (OCNotifications *notification in appDelegate.listOfNotifications)
  839. old = [old stringByAppendingString:@(notification.idNotification).stringValue];
  840. if (![new isEqualToString:old]) {
  841. appDelegate.listOfNotifications = [[NSMutableArray alloc] initWithArray:sortedListOfNotifications];
  842. // reload Notification view
  843. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"notificationReloadData" object:nil];
  844. }
  845. // Update NavigationBar
  846. if (!_isSelectedMode) {
  847. [self performSelectorOnMainThread:@selector(setUINavigationBarDefault) withObject:nil waitUntilDone:NO];
  848. }
  849. });
  850. }
  851. - (void)getNotificationServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  852. {
  853. // Update NavigationBar
  854. if (!_isSelectedMode)
  855. [self setUINavigationBarDefault];
  856. }
  857. - (void)viewNotification
  858. {
  859. if ([app.listOfNotifications count] > 0) {
  860. CCNotification *notificationVC = [[UIStoryboard storyboardWithName:@"CCNotification" bundle:nil] instantiateViewControllerWithIdentifier:@"CCNotification"];
  861. [notificationVC setModalPresentationStyle:UIModalPresentationFormSheet];
  862. [self presentViewController:notificationVC animated:YES completion:nil];
  863. }
  864. }
  865. #pragma --------------------------------------------------------------------------------------------
  866. #pragma mark ==== User Profile ====
  867. #pragma --------------------------------------------------------------------------------------------
  868. - (void)getUserProfileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  869. {
  870. if (errorCode == 401)
  871. [self changePasswordAccount];
  872. }
  873. - (void)getUserProfileSuccess:(CCMetadataNet *)metadataNet userProfile:(OCUserProfile *)userProfile
  874. {
  875. [[NCManageDatabase sharedInstance] setAccountsUserProfile:userProfile];
  876. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  877. NSString *address = [NSString stringWithFormat:@"%@/index.php/avatar/%@/128", app.activeUrl, app.activeUser];
  878. UIImage *avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
  879. if (avatar)
  880. [UIImagePNGRepresentation(avatar) writeToFile:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] atomically:YES];
  881. else
  882. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] error:nil];
  883. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"changeUserProfile" object:nil];
  884. });
  885. }
  886. #pragma --------------------------------------------------------------------------------------------
  887. #pragma mark ==== Capabilities ====
  888. #pragma --------------------------------------------------------------------------------------------
  889. - (void)getCapabilitiesOfServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  890. {
  891. // Change Theming color
  892. [app settingThemingColorBrand];
  893. if (errorCode == 401)
  894. [self changePasswordAccount];
  895. }
  896. - (void)getCapabilitiesOfServerSuccess:(OCCapabilities *)capabilities
  897. {
  898. // Update capabilities db
  899. [[NCManageDatabase sharedInstance] addCapabilities:capabilities];
  900. // ------ THEMING -----------------------------------------------------------------------
  901. // Download Theming Background & Change Theming color
  902. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  903. if ([NCBrandOptions sharedInstance].use_themingBackground == YES) {
  904. UIImage *themingBackground = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[capabilities.themingBackground stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
  905. if (themingBackground)
  906. [UIImagePNGRepresentation(themingBackground) writeToFile:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] atomically:YES];
  907. else
  908. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] error:nil];
  909. }
  910. dispatch_async(dispatch_get_main_queue(), ^{
  911. [app settingThemingColorBrand];
  912. });
  913. });
  914. // ------ SEARCH ------------------------------------------------------------------------
  915. // Search bar if change version
  916. if ([[NCManageDatabase sharedInstance] getServerVersion] != capabilities.versionMajor) {
  917. [self cancelSearchBar];
  918. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  919. if (capabilities.versionMajor >= 12) {
  920. if (_isRoot)
  921. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_all_folders_",nil);
  922. else
  923. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_sub_folder_",nil);
  924. self.searchController.searchBar.scopeButtonTitles = [NSArray arrayWithObjects:NSLocalizedString(@"_search_this_folder_",nil),self.searchController.searchBar.placeholder, nil];
  925. } else {
  926. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_this_folder_",nil);
  927. self.searchController.searchBar.scopeButtonTitles = nil;
  928. }
  929. _depth = @"0";
  930. });
  931. }
  932. // ------ GET SERVICE SERVER ------------------------------------------------------------
  933. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  934. // Read External Sites
  935. if (capabilities.isExternalSitesServerEnabled) {
  936. metadataNet.action = actionGetExternalSitesServer;
  937. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  938. }
  939. // Read Share
  940. if (capabilities.isFilesSharingAPIEnabled) {
  941. [app.sharesID removeAllObjects];
  942. metadataNet.action = actionReadShareServer;
  943. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  944. }
  945. // Read Notification
  946. metadataNet.action = actionGetNotificationServer;
  947. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  948. // Read User Profile
  949. metadataNet.action = actionGetUserProfile;
  950. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  951. // Read Activity
  952. metadataNet.action = actionGetActivityServer;
  953. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  954. }
  955. #pragma mark -
  956. #pragma --------------------------------------------------------------------------------------------
  957. #pragma mark ==== Request Server Information ====
  958. #pragma --------------------------------------------------------------------------------------------
  959. - (void)requestServerCapabilities
  960. {
  961. // test
  962. if (app.activeAccount.length == 0)
  963. return;
  964. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  965. metadataNet.action = actionGetCapabilities;
  966. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  967. }
  968. #pragma mark -
  969. #pragma --------------------------------------------------------------------------------------------
  970. #pragma mark ==== Middleware Ping ====
  971. #pragma --------------------------------------------------------------------------------------------
  972. - (void)middlewarePing
  973. {
  974. // test
  975. if (app.activeAccount.length == 0)
  976. return;
  977. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  978. metadataNet.action = actionMiddlewarePing;
  979. metadataNet.serverUrl = [[NCBrandOptions sharedInstance] middlewarePingUrl];
  980. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  981. }
  982. #pragma mark -
  983. #pragma --------------------------------------------------------------------------------------------
  984. #pragma mark ==== Download Thumbnail Delegate ====
  985. #pragma --------------------------------------------------------------------------------------------
  986. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  987. {
  988. __block CCCellMain *cell;
  989. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  990. if (indexPath && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]]) {
  991. cell = [self.tableView cellForRowAtIndexPath:indexPath];
  992. cell.file.image = [app.icoImagesCache objectForKey:metadataNet.fileID];
  993. if (cell.file.image == nil) {
  994. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  995. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]];
  996. [app.icoImagesCache setObject:image forKey:metadataNet.fileID];
  997. });
  998. }
  999. }
  1000. }
  1001. #pragma --------------------------------------------------------------------------------------------
  1002. #pragma mark ==== Download ====
  1003. #pragma --------------------------------------------------------------------------------------------
  1004. - (void)downloadFileFailure:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1005. {
  1006. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1007. // File do not exists on server, remove in local
  1008. if (errorCode == kOCErrorServerPathNotFound || errorCode == kCFURLErrorBadServerResponse) {
  1009. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID] error:nil];
  1010. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, fileID] error:nil];
  1011. if (metadata.directory && serverUrl) {
  1012. NSString *dirForDelete = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileNameData];
  1013. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:dirForDelete];
  1014. }
  1015. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID] clearDateReadDirectoryID:nil];
  1016. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1017. }
  1018. if ([selector isEqualToString:selectorLoadViewImage]) {
  1019. dispatch_async(dispatch_get_main_queue(), ^{
  1020. // Updating Detail
  1021. if (app.activeDetail)
  1022. [app.activeDetail downloadPhotoBrowserFailure:errorCode];
  1023. // Updating Photos
  1024. if (app.activePhotos)
  1025. [app.activePhotos downloadFileFailure:errorCode];
  1026. });
  1027. } else {
  1028. if (errorCode != kCFURLErrorCancelled)
  1029. [app messageNotification:@"_download_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1030. }
  1031. [self reloadDatasource:serverUrl fileID:fileID selector:selector];
  1032. }
  1033. - (void)downloadFileSuccess:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1034. {
  1035. __block tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1036. if (metadata == nil) return;
  1037. // Download
  1038. if ([selector isEqualToString:selectorDownloadFile]) {
  1039. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1040. }
  1041. // Synchronized
  1042. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  1043. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1044. }
  1045. // add Favorite
  1046. if ([selector isEqualToString:selectorAddFavorite]) {
  1047. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  1048. }
  1049. // encrypted file
  1050. if ([selector isEqualToString:selectorEncryptFile]) {
  1051. [self encryptedFile:metadata];
  1052. }
  1053. // decrypted file
  1054. if ([selector isEqualToString:selectorDecryptFile]) {
  1055. [self decryptedFile:metadata];
  1056. }
  1057. // open View File
  1058. if ([selector isEqualToString:selectorLoadFileView] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1059. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1060. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_compress]) {
  1061. selector = selectorOpenIn;
  1062. //[self performSelector:@selector(unZipFile:) withObject:metadata.fileID];
  1063. } else if ([metadata.typeFile isEqualToString: k_metadataTypeFile_unknown]) {
  1064. selector = selectorOpenIn;
  1065. } else {
  1066. _metadata = metadata;
  1067. if ([self shouldPerformSegue])
  1068. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  1069. }
  1070. }
  1071. // addLocal
  1072. if ([selector isEqualToString:selectorAddLocal]) {
  1073. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  1074. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  1075. [CCGraphics saveIcoWithEtag:metadata.fileNamePrint image:image writeToFile:nil copy:YES move:NO fromPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/.%@.ico", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  1076. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  1077. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1078. }
  1079. // Open with...
  1080. if ([selector isEqualToString:selectorOpenIn] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1081. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1082. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1083. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1084. NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint]];
  1085. _docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  1086. _docController.delegate = self;
  1087. [_docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  1088. }
  1089. // Save to Photo Album
  1090. if ([selector isEqualToString:selectorSave] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1091. NSString *file = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1092. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  1093. // evitiamo il rimando photo
  1094. [[NCManageDatabase sharedInstance] setAccountAutoUploadDateAssetType:PHAssetMediaTypeImage assetDate:[NSDate date]];
  1095. UIImage *image = [UIImage imageWithContentsOfFile:file];
  1096. if (image)
  1097. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1098. else
  1099. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1100. }
  1101. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  1102. // we avoid the cross-reference video
  1103. [[NCManageDatabase sharedInstance] setAccountAutoUploadDateAssetType:PHAssetMediaTypeVideo assetDate:[NSDate date]];
  1104. [[NSFileManager defaultManager] linkItemAtPath:file toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1105. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint])) {
  1106. UISaveVideoAtPathToSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint], self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1107. } else {
  1108. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1109. }
  1110. }
  1111. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1112. }
  1113. // Copy File
  1114. if ([selector isEqualToString:selectorLoadCopy]) {
  1115. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1116. [self copyFileToPasteboard:metadata];
  1117. }
  1118. // download and view a template
  1119. if ([selector isEqualToString:selectorLoadModelView]) {
  1120. // se è un template aggiorniamo anche nel FileSystem
  1121. if ([metadata.type isEqualToString: k_metadataType_template]) {
  1122. [[NCManageDatabase sharedInstance] setLocalFileWithFileID:metadata.fileID date:metadata.date exifDate:nil exifLatitude:nil exifLongitude:nil fileName:nil fileNamePrint:metadata.fileNamePrint];
  1123. }
  1124. [self openModel:metadata.model isNew:false];
  1125. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1126. }
  1127. //download file plist
  1128. if ([selector isEqualToString:selectorLoadPlist]) {
  1129. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1130. long countSelectorLoadPlist = 0;
  1131. for (NSOperation *operation in [app.netQueue operations]) {
  1132. if ([((OCnetworking *)operation).metadataNet.selector isEqualToString:selectorLoadPlist])
  1133. countSelectorLoadPlist++;
  1134. }
  1135. if ((countSelectorLoadPlist == 0 || countSelectorLoadPlist % k_maxConcurrentOperation == 0) && [metadata.directoryID isEqualToString:[[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl]]) {
  1136. dispatch_async(dispatch_get_main_queue(), ^{
  1137. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1138. });
  1139. }
  1140. });
  1141. }
  1142. //selectorLoadViewImage
  1143. if ([selector isEqualToString:selectorLoadViewImage]) {
  1144. // Detail
  1145. if (app.activeDetail)
  1146. [app.activeDetail downloadPhotoBrowserSuccess:metadata selector:selector];
  1147. // Photos
  1148. if (app.activePhotos)
  1149. [app.activePhotos downloadFileSuccess:metadata];
  1150. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1151. }
  1152. // if exists postselector call self with selectorPost
  1153. if ([selectorPost length] > 0)
  1154. [self downloadFileSuccess:fileID serverUrl:serverUrl selector:selectorPost selectorPost:nil];
  1155. }
  1156. - (void)downloadSelectedFiles
  1157. {
  1158. NSLog(@"[LOG] Start download selected files ...");
  1159. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1160. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1161. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1162. for (tableMetadata *metadata in selectedMetadatas) {
  1163. if (metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_file]) {
  1164. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1165. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorDownloadFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1166. }
  1167. }
  1168. [_hud hideHud];
  1169. });
  1170. [self tableViewSelect:NO];
  1171. }
  1172. - (void)downloadPlist:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1173. {
  1174. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session = ''", app.activeAccount, directoryID] sorted:nil ascending:NO];
  1175. for (tableMetadata *metadata in metadatas) {
  1176. if ([CCUtility isCryptoPlistString:metadata.fileName] && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName]] == NO && [metadata.session length] == 0) {
  1177. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1178. metadataNet.action = actionDownloadFile;
  1179. metadataNet.downloadData = NO;
  1180. metadataNet.downloadPlist = YES;
  1181. metadataNet.fileID = metadata.fileID;
  1182. metadataNet.selector = selectorLoadPlist;
  1183. metadataNet.serverUrl = serverUrl;
  1184. metadataNet.session = k_download_session_foreground;
  1185. metadataNet.taskStatus = k_taskStatusResume;
  1186. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1187. //[[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:NO downloadPlist:YES selector:selectorLoadPlist selectorPost:nil session:k_download_session_foreground taskStatus:k_taskStatusResume delegate:self];
  1188. }
  1189. }
  1190. }
  1191. #pragma --------------------------------------------------------------------------------------------
  1192. #pragma mark ===== Upload new Photos/Videos =====
  1193. #pragma --------------------------------------------------------------------------------------------
  1194. - (void)uploadFileFailure:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1195. {
  1196. // Auto Upload
  1197. if([selector isEqualToString:selectorUploadAutoUpload] || [selector isEqualToString:selectorUploadAutoUploadAll]) {
  1198. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1199. // ONLY BACKGROUND
  1200. [[NCAutoUpload sharedInstance] performSelectorOnMainThread:@selector(loadAutoUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1201. } else {
  1202. // ONLY FOREFROUND
  1203. [[NCAutoUpload sharedInstance] performSelectorOnMainThread:@selector(loadAutoUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1204. }
  1205. }
  1206. // Read File test do not exists
  1207. if (errorCode == k_CCErrorFileUploadNotFound && fileID) {
  1208. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1209. // reUpload
  1210. if (metadata)
  1211. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  1212. }
  1213. // Print error
  1214. else if (errorCode != kCFURLErrorCancelled && errorCode != 403) {
  1215. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1216. }
  1217. [self reloadDatasource:serverUrl fileID:nil selector:selector];
  1218. }
  1219. - (void)uploadFileSuccess:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1220. {
  1221. // Auto Upload
  1222. if([selector isEqualToString:selectorUploadAutoUpload] || [selector isEqualToString:selectorUploadAutoUploadAll]) {
  1223. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1224. // ONLY BACKGROUND
  1225. [[NCAutoUpload sharedInstance] performSelectorOnMainThread:@selector(loadAutoUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1226. } else {
  1227. // ONLY FOREFROUND
  1228. [[NCAutoUpload sharedInstance] performSelectorOnMainThread:@selector(loadAutoUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1229. }
  1230. }
  1231. if ([selectorPost isEqualToString:selectorReadFolderForced] ) {
  1232. [self readFolderWithForced:YES serverUrl:serverUrl];
  1233. } else {
  1234. [self reloadDatasource:serverUrl fileID:nil selector:selector];
  1235. }
  1236. }
  1237. //
  1238. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  1239. //
  1240. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  1241. {
  1242. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
  1243. [self performSelectorOnMainThread:@selector(uploadFileAssetBridge:) withObject:@[assets, serverUrl, [NSNumber numberWithBool:cryptated], [NSNumber numberWithBool:useSubFolder], session] waitUntilDone:NO];
  1244. });
  1245. }
  1246. - (void)uploadFileAssetBridge:(NSArray *)arguments
  1247. {
  1248. NSArray *assets = [arguments objectAtIndex:0];
  1249. NSString *serverUrl = [arguments objectAtIndex:1];
  1250. BOOL cryptated = [[arguments objectAtIndex:2] boolValue];
  1251. BOOL useSubFolder = [[arguments objectAtIndex:3] boolValue];
  1252. NSString *session = [arguments objectAtIndex:4];
  1253. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  1254. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  1255. // Create the folder for Photos & if request the subfolders
  1256. if (![[NCAutoUpload sharedInstance] createFolderSubFolderAutoUploadFolderPhotos:autoUploadPath useSubFolder:useSubFolder assets:assets selector:selectorUploadFile])
  1257. return;
  1258. NSLog(@"[LOG] Asset N. %lu", (unsigned long)[assets count]);
  1259. for (PHAsset *asset in assets) {
  1260. NSString *fileName = [CCUtility createFileNameFromAsset:asset key: k_keyFileNameMask];
  1261. NSDate *assetDate = asset.creationDate;
  1262. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1263. // Create serverUrl if use sub folder
  1264. if (useSubFolder) {
  1265. [formatter setDateFormat:@"yyyy"];
  1266. NSString *yearString = [formatter stringFromDate:assetDate];
  1267. [formatter setDateFormat:@"MM"];
  1268. NSString *monthString = [formatter stringFromDate:assetDate];
  1269. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  1270. }
  1271. // Check if is in upload
  1272. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@ AND session != ''", app.activeAccount, directoryID, fileName];
  1273. NSArray *isRecordInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1274. if ([isRecordInSessions count] > 0) {
  1275. // next upload
  1276. continue;
  1277. } else {
  1278. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1279. if (cryptated) {
  1280. metadataNet.action = actionUploadAsset;
  1281. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1282. metadataNet.cryptated = cryptated;
  1283. metadataNet.fileName = fileName;
  1284. metadataNet.priority = NSOperationQueuePriorityNormal;
  1285. metadataNet.session = session;
  1286. metadataNet.selector = selectorUploadFile;
  1287. metadataNet.selectorPost = nil;
  1288. metadataNet.serverUrl = serverUrl;
  1289. metadataNet.taskStatus = k_taskStatusResume;
  1290. } else {
  1291. metadataNet.action = actionReadFile;
  1292. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1293. metadataNet.cryptated = cryptated;
  1294. metadataNet.fileName = fileName;
  1295. metadataNet.priority = NSOperationQueuePriorityNormal;
  1296. metadataNet.session = session;
  1297. metadataNet.selector = selectorReadFileUploadFile;
  1298. metadataNet.serverUrl = serverUrl;
  1299. }
  1300. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1301. }
  1302. }
  1303. }
  1304. #pragma --------------------------------------------------------------------------------------------
  1305. #pragma mark ==== Read File ====
  1306. #pragma --------------------------------------------------------------------------------------------
  1307. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1308. {
  1309. // UploadFile
  1310. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1311. // File not exists
  1312. if (errorCode == 404) {
  1313. metadataNet.action = actionUploadAsset;
  1314. metadataNet.errorCode = 0;
  1315. metadataNet.selector = selectorUploadFile;
  1316. metadataNet.selectorPost = nil;
  1317. metadataNet.taskStatus = k_taskStatusResume;
  1318. if ([metadataNet.session containsString:@"wwan"])
  1319. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1320. else
  1321. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1322. } else {
  1323. // error ho many retry befor notification and go to on next asses
  1324. if (metadataNet.errorRetry < 3) {
  1325. // Retry read file
  1326. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1327. } else {
  1328. // STOP check file, view message error
  1329. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1330. }
  1331. }
  1332. }
  1333. }
  1334. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(tableMetadata *)metadata
  1335. {
  1336. // UploadFile
  1337. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1338. metadataNet.action = actionUploadAsset;
  1339. metadataNet.errorCode = 403; // File exists 403 Forbidden
  1340. metadataNet.selector = selectorUploadFile;
  1341. metadataNet.selectorPost = nil;
  1342. metadataNet.taskStatus = k_taskStatusResume;
  1343. if ([metadataNet.session containsString:@"wwan"])
  1344. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1345. else
  1346. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1347. }
  1348. }
  1349. #pragma --------------------------------------------------------------------------------------------
  1350. #pragma mark ==== Read Folder ====
  1351. #pragma --------------------------------------------------------------------------------------------
  1352. - (void)readFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1353. {
  1354. // verify active user
  1355. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1356. [_hud hideHud];
  1357. [_refreshControl endRefreshing];
  1358. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1359. if (message && [record.account isEqualToString:metadataNet.account])
  1360. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1361. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1362. if (errorCode == 401)
  1363. [self changePasswordAccount];
  1364. }
  1365. - (void)readFolderSuccess:(CCMetadataNet *)metadataNet permissions:(NSString *)permissions etag:(NSString *)etag metadatas:(NSArray *)metadatas
  1366. {
  1367. // verify active user
  1368. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1369. if (![record.account isEqualToString:metadataNet.account])
  1370. return;
  1371. // save father e update permission
  1372. if(!_isSearchMode)
  1373. _fatherPermission = permissions;
  1374. NSArray *recordsInSessions;
  1375. NSMutableArray *metadatasToInsertInDB = [NSMutableArray new];
  1376. if (_isSearchMode) {
  1377. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", metadataNet.account] sorted:nil ascending:NO];
  1378. } else {
  1379. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:metadataNet.serverUrl serverUrlTo:nil etag:etag];
  1380. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session = ''", metadataNet.account, metadataNet.directoryID] clearDateReadDirectoryID:metadataNet.directoryID];
  1381. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session != ''", metadataNet.account, metadataNet.directoryID] sorted:nil ascending:NO];
  1382. [[NCManageDatabase sharedInstance] setDateReadDirectoryWithDirectoryID:metadataNet.directoryID];
  1383. }
  1384. for (tableMetadata *metadata in metadatas) {
  1385. // type of file
  1386. NSInteger typeFilename = [CCUtility getTypeFileName:metadata.fileName];
  1387. // if crypto do not insert
  1388. if (typeFilename == k_metadataTypeFilenameCrypto) continue;
  1389. // verify if the record encrypted has plist + crypto
  1390. if (typeFilename == k_metadataTypeFilenamePlist && metadata.directory == NO) {
  1391. BOOL isCryptoComplete = NO;
  1392. NSString *fileNameCrypto = [CCUtility trasformedFileNamePlistInCrypto:metadata.fileName];
  1393. for (tableMetadata *completeMetadata in metadatas) {
  1394. if (completeMetadata.cryptated == NO) continue;
  1395. else if ([completeMetadata.fileName isEqualToString:fileNameCrypto]) {
  1396. isCryptoComplete = YES;
  1397. break;
  1398. }
  1399. }
  1400. if (isCryptoComplete == NO) continue;
  1401. }
  1402. // verify if the record is in download/upload progress
  1403. if (metadata.directory == NO && [recordsInSessions count] > 0) {
  1404. tableMetadata *metadataTransfer = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@", app.activeAccount, metadataNet.directoryID, metadata.fileName]];
  1405. // is in Download or Upload
  1406. if ([metadataTransfer.session containsString:@"upload"] || [metadataTransfer.session containsString:@"download"]) {
  1407. continue;
  1408. }
  1409. }
  1410. // Insert in Array
  1411. [metadatasToInsertInDB addObject:metadata];
  1412. }
  1413. // insert in Database
  1414. metadatasToInsertInDB = (NSMutableArray *)[[NCManageDatabase sharedInstance] addMetadatas:metadatasToInsertInDB activeUrl:app.activeUrl serverUrl:metadataNet.serverUrl];
  1415. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1416. // read plist
  1417. if (!_isSearchMode)
  1418. [self downloadPlist:metadataNet.directoryID serverUrl:metadataNet.serverUrl];
  1419. // File is changed ??
  1420. if (!_isSearchMode && metadatasToInsertInDB)
  1421. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl account:app.activeAccount withDownload:NO];
  1422. });
  1423. // Search Mode
  1424. if (_isSearchMode)
  1425. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1426. // this is the same directory
  1427. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  1428. // reload
  1429. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1430. // stoprefresh
  1431. [_refreshControl endRefreshing];
  1432. // Enable change user
  1433. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1434. [_hud hideHud];
  1435. }
  1436. }
  1437. - (void)readFolderWithForced:(BOOL)forced serverUrl:(NSString *)serverUrl
  1438. {
  1439. // init control
  1440. if (!serverUrl || !app.activeAccount || app.maintenanceMode) {
  1441. [_hud hideHud];
  1442. [_refreshControl endRefreshing];
  1443. return;
  1444. }
  1445. // Search Mode
  1446. if (_isSearchMode) {
  1447. if (forced) {
  1448. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl directoryID:nil];
  1449. _searchFileName = @""; // forced reload searchg
  1450. }
  1451. [self updateSearchResultsForSearchController:self.searchController];
  1452. return;
  1453. }
  1454. BOOL isDirectoryOutOfDate = true;
  1455. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", serverUrl]];
  1456. if (directory.dateReadDirectory) {
  1457. // Is Directory Out Of Date ?
  1458. NSDateComponents *dateComponents = [NSDateComponents new];
  1459. [dateComponents setWeekday:k_dayForceReadFolder];
  1460. NSCalendar *calendar = [NSCalendar currentCalendar];
  1461. NSDate *datePlus = [calendar dateByAddingComponents:dateComponents toDate:directory.dateReadDirectory options:0];
  1462. NSDate *now = [NSDate date];
  1463. // usa la Cache se richiesto e se la data è entro X giorni dall'ultima volta che l'hai letta.
  1464. if ([now compare:datePlus] == NSOrderedDescending)
  1465. isDirectoryOutOfDate = true;
  1466. else
  1467. isDirectoryOutOfDate = false;
  1468. }
  1469. if (isDirectoryOutOfDate || forced) {
  1470. if (_refreshControl.isRefreshing == NO)
  1471. [_hud visibleIndeterminateHud];
  1472. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1473. metadataNet.action = actionReadFolder;
  1474. metadataNet.date = [NSDate date];
  1475. metadataNet.directoryID = directory.directoryID;
  1476. metadataNet.priority = NSOperationQueuePriorityHigh;
  1477. metadataNet.selector = selectorReadFolder;
  1478. metadataNet.serverUrl = serverUrl;
  1479. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1480. }
  1481. }
  1482. #pragma mark -
  1483. #pragma --------------------------------------------------------------------------------------------
  1484. #pragma mark ===== Search =====
  1485. #pragma --------------------------------------------------------------------------------------------
  1486. -(void)searchStartTimer
  1487. {
  1488. [[CCActions sharedInstance] search:_serverUrl fileName:_searchFileName depth:_depth date:nil selector:selectorSearch delegate:self];
  1489. _noFilesSearchTitle = @"";
  1490. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1491. [self.tableView reloadEmptyDataSet];
  1492. }
  1493. -(void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1494. {
  1495. _isSearchMode = YES;
  1496. [self deleteRefreshControl];
  1497. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1498. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1499. _searchFileName = fileName;
  1500. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12 && ![_depth isEqualToString:@"0"]) {
  1501. [_timerWaitInput invalidate];
  1502. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  1503. } else {
  1504. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1505. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"directoryID = %@ AND account = %@ AND fileNamePrint CONTAINS[cd] %@", directoryID, app.activeAccount, fileName];
  1506. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1507. [_searchResultMetadatas removeAllObjects];
  1508. for (tableMetadata *record in records)
  1509. [_searchResultMetadatas addObject:record];
  1510. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1511. metadataNet.account = app.activeAccount;
  1512. metadataNet.action = actionUploadTemplate;
  1513. metadataNet.directoryID = directoryID;
  1514. metadataNet.selector = selectorSearch;
  1515. metadataNet.serverUrl = _serverUrl;
  1516. [self readFolderSuccess:metadataNet permissions:@"" etag:@"" metadatas:_searchResultMetadatas];
  1517. }
  1518. }
  1519. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1520. [self reloadDatasource];
  1521. }
  1522. }
  1523. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1524. {
  1525. [self cancelSearchBar];
  1526. [self readFolderWithForced:NO serverUrl:_serverUrl];
  1527. }
  1528. - (void)searchFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1529. {
  1530. _searchFileName = @"";
  1531. if (message)
  1532. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1533. }
  1534. - (void)searchSuccess:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas
  1535. {
  1536. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1537. [self readFolderSuccess:metadataNet permissions:nil etag:nil metadatas:metadatas];
  1538. }
  1539. - (void)cancelSearchBar
  1540. {
  1541. if (self.searchController.active) {
  1542. [self.searchController setActive:NO];
  1543. [self createRefreshControl];
  1544. _isSearchMode = NO;
  1545. _searchFileName = @"";
  1546. _dateReadDataSource = nil;
  1547. _searchResultMetadatas = [NSMutableArray new];
  1548. [self reloadDatasource];
  1549. }
  1550. }
  1551. - (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope
  1552. {
  1553. NSString *title = [self.searchController.searchBar.scopeButtonTitles objectAtIndex:selectedScope];
  1554. self.searchController.searchBar.placeholder = title;
  1555. if ([title isEqualToString:NSLocalizedString(@"_search_this_folder_",nil)])
  1556. _depth = @"0";
  1557. if ([title isEqualToString:NSLocalizedString(@"_search_sub_folder_",nil)])
  1558. _depth = @"1";
  1559. if ([title isEqualToString:NSLocalizedString(@"_search_all_folders_",nil)])
  1560. _depth = @"infinity";
  1561. _searchFileName = @"";
  1562. [self updateSearchResultsForSearchController:self.searchController];
  1563. }
  1564. #pragma mark -
  1565. #pragma --------------------------------------------------------------------------------------------
  1566. #pragma mark ===== Delete File or Folder =====
  1567. #pragma --------------------------------------------------------------------------------------------
  1568. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1569. {
  1570. [self deleteFileOrFolderSuccess:metadataNet];
  1571. }
  1572. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  1573. {
  1574. [_queueSelector removeObject:metadataNet.selector];
  1575. if ([_queueSelector count] == 0) {
  1576. [_hud hideHud];
  1577. if (_isSearchMode)
  1578. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1579. else
  1580. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  1581. // next
  1582. if ([_selectedMetadatas count] > 0) {
  1583. [_selectedMetadatas removeObjectAtIndex:0];
  1584. if ([_selectedMetadatas count] > 0)
  1585. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1586. }
  1587. }
  1588. }
  1589. - (void)deleteFileOrFolder:(tableMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1590. {
  1591. if (metadata.cryptated) {
  1592. [_queueSelector addObject:selectorDeleteCrypto];
  1593. [_queueSelector addObject:selectorDeletePlist];
  1594. } else {
  1595. [_queueSelector addObject:selectorDelete];
  1596. }
  1597. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  1598. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1599. }
  1600. - (void)deleteSelectionFile
  1601. {
  1602. [_selectedMetadatas removeAllObjects];
  1603. [_queueSelector removeAllObjects];
  1604. _selectedMetadatas = [[NSMutableArray alloc] initWithArray: [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]]];
  1605. _numSelectedMetadatas = [_selectedMetadatas count];
  1606. if ([_selectedMetadatas count] > 0)
  1607. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1608. [self tableViewSelect:NO];
  1609. }
  1610. - (void)deleteFile
  1611. {
  1612. [_selectedMetadatas removeAllObjects];
  1613. [_queueSelector removeAllObjects];
  1614. _numSelectedMetadatas = 1;
  1615. [_selectedMetadatas addObject:_metadata];
  1616. if ([_selectedMetadatas count] > 0)
  1617. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1618. [self tableViewSelect:NO];
  1619. }
  1620. #pragma --------------------------------------------------------------------------------------------
  1621. #pragma mark ===== Rename / Move =====
  1622. #pragma --------------------------------------------------------------------------------------------
  1623. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1624. {
  1625. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1626. }
  1627. - (void)renameFile:(NSArray *)arguments
  1628. {
  1629. tableMetadata* metadata = [arguments objectAtIndex:0];
  1630. NSString *fileName = [arguments objectAtIndex:1];
  1631. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1632. }
  1633. - (void)renameNote:(NSArray *)arguments
  1634. {
  1635. tableMetadata* metadata = [arguments objectAtIndex:0];
  1636. NSString *fileName = [arguments objectAtIndex:1];
  1637. CCTemplates *templates = [[CCTemplates alloc] init];
  1638. NSMutableDictionary *field = [[CCCrypto sharedManager] getDictionaryEncrypted:metadata.fileName uuid:metadata.uuid isLocal:NO directoryUser:app.directoryUser];
  1639. NSString *fileNameModel = [templates salvaNote:[field objectForKey:@"note"] titolo:fileName fileName:metadata.fileName uuid:metadata.uuid];
  1640. if (fileNameModel) {
  1641. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1642. metadataNet.action = actionUploadTemplate;
  1643. metadataNet.fileName = [CCUtility trasformedFileNamePlistInCrypto:fileNameModel];
  1644. metadataNet.fileNamePrint = fileName;
  1645. metadataNet.etag = metadata.etag;
  1646. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1647. metadataNet.session = k_upload_session_foreground;
  1648. metadataNet.taskStatus = k_taskStatusResume;
  1649. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1650. }
  1651. }
  1652. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1653. {
  1654. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1655. [_hud hideHud];
  1656. if (message)
  1657. [app messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1658. [_selectedMetadatas removeAllObjects];
  1659. [_queueSelector removeAllObjects];
  1660. }
  1661. }
  1662. - (void)moveSuccess:(CCMetadataNet *)metadataNet
  1663. {
  1664. [_queueSelector removeObject:metadataNet.selector];
  1665. if ([_queueSelector count] == 0) {
  1666. [_hud hideHud];
  1667. NSString *fileName = [CCUtility trasformedFileNameCryptoInPlist:metadataNet.fileName];
  1668. NSString *directoryID = metadataNet.directoryID;
  1669. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1670. NSString *serverUrlTo = [[NCManageDatabase sharedInstance] getServerUrl:directoryIDTo];
  1671. // FILE -> Metadata
  1672. if (metadataNet.directory == NO) {
  1673. // move metadata
  1674. //[CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1675. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1676. }
  1677. // DIRECTORY -> Directory - CCMetadata
  1678. if (metadataNet.directory == YES) {
  1679. // delete all dir / subdir
  1680. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName]];
  1681. // move metadata
  1682. //[CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1683. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1684. // Add new directory
  1685. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1686. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:@""];
  1687. }
  1688. // reload Datasource
  1689. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1690. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1691. else
  1692. [self reloadDatasource];
  1693. // Next file
  1694. [_selectedMetadatas removeObjectAtIndex:0];
  1695. [self performSelectorOnMainThread:@selector(moveFileOrFolder:) withObject:metadataNet.serverUrlTo waitUntilDone:NO];
  1696. }
  1697. }
  1698. - (void)moveFileOrFolder:(NSString *)serverUrlTo
  1699. {
  1700. if ([_selectedMetadatas count] > 0) {
  1701. tableMetadata *metadata = [_selectedMetadatas objectAtIndex:0];
  1702. // Plain
  1703. if (metadata.cryptated == NO) {
  1704. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:app.activeUser withPassword:app.activePassword withUrl:app.activeUrl isCryptoCloudMode:NO];
  1705. NSError *error = [ocNetworking readFileSync:[NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName]];
  1706. if(!error) {
  1707. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1708. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1709. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1710. }];
  1711. [alert addAction:ok];
  1712. [self presentViewController:alert animated:YES completion:nil];
  1713. });
  1714. return;
  1715. }
  1716. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1717. metadataNet.action = actionMoveFileOrFolder;
  1718. metadataNet.directory = metadata.directory;
  1719. metadataNet.fileID = metadata.fileID;
  1720. metadataNet.directoryID = metadata.directoryID;
  1721. metadataNet.directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1722. metadataNet.fileName = metadata.fileName;
  1723. metadataNet.fileNamePrint = metadataNet.fileNamePrint;
  1724. metadataNet.fileNameTo = metadata.fileName;
  1725. metadataNet.etag = metadata.etag;
  1726. metadataNet.selector = selectorMove;
  1727. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1728. metadataNet.serverUrlTo = serverUrlTo;
  1729. [_queueSelector addObject:metadataNet.selector];
  1730. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1731. }
  1732. // cyptated
  1733. if (metadata.cryptated == YES) {
  1734. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1735. metadataNet.action = actionMoveFileOrFolder;
  1736. metadataNet.directory = metadata.directory;
  1737. metadataNet.fileID = metadata.fileID;
  1738. metadataNet.directoryID = metadata.directoryID;
  1739. metadataNet.directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1740. metadataNet.fileNamePrint = metadata.fileNamePrint;
  1741. metadataNet.etag = metadata.etag;
  1742. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1743. metadataNet.serverUrlTo = serverUrlTo;
  1744. // data
  1745. metadataNet.fileName = metadata.fileNameData;
  1746. metadataNet.fileNameTo = metadata.fileNameData;
  1747. metadataNet.selector = selectorMoveCrypto;
  1748. [_queueSelector addObject:metadataNet.selector];
  1749. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1750. // plist
  1751. metadataNet.fileName = metadata.fileName;
  1752. metadataNet.fileNameTo = metadata.fileName;
  1753. metadataNet.selector = selectorMovePlist;
  1754. [_queueSelector addObject:metadataNet.selector];
  1755. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1756. }
  1757. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), _numSelectedMetadatas - [_selectedMetadatas count] + 1, _numSelectedMetadatas] mode:MBProgressHUDModeIndeterminate color:nil];
  1758. }
  1759. }
  1760. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title selectedMetadatas:(NSArray *)selectedMetadatas
  1761. {
  1762. [_selectedMetadatas removeAllObjects];
  1763. [_queueSelector removeAllObjects];
  1764. _selectedMetadatas = [[NSMutableArray alloc] initWithArray:selectedMetadatas];
  1765. _numSelectedMetadatas = [_selectedMetadatas count];
  1766. [self performSelectorOnMainThread:@selector(moveFileOrFolder:) withObject:serverUrlTo waitUntilDone:NO];
  1767. [self tableViewSelect:NO];
  1768. }
  1769. - (void)moveOpenWindow:(NSArray *)indexPaths
  1770. {
  1771. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1772. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1773. viewController.delegate = self;
  1774. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1775. viewController.selectedMetadatas = [self getMetadatasFromSelectedRows:indexPaths];
  1776. viewController.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  1777. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  1778. viewController.tintColorTitle = [NCBrandColor sharedInstance].navigationBarText;
  1779. viewController.networkingOperationQueue = app.netQueue;
  1780. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1781. [self presentViewController:navigationController animated:YES completion:nil];
  1782. }
  1783. #pragma --------------------------------------------------------------------------------------------
  1784. #pragma mark ===== Create folder =====
  1785. #pragma --------------------------------------------------------------------------------------------
  1786. - (void)createFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1787. {
  1788. [_hud hideHud];
  1789. if (message)
  1790. [app messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1791. }
  1792. - (void)createFolderSuccess:(CCMetadataNet *)metadataNet
  1793. {
  1794. [_hud hideHud];
  1795. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1796. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:@""];
  1797. // Load Folder or the Datasource
  1798. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced]) {
  1799. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1800. } else {
  1801. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  1802. }
  1803. }
  1804. - (void)createFolder:(NSString *)fileNameFolder autoUploadDirectory:(BOOL)autoUploadDirectory
  1805. {
  1806. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1807. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1808. if (![fileNameFolder length]) return;
  1809. if (autoUploadDirectory) metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  1810. else metadataNet.serverUrl = _serverUrl;
  1811. metadataNet.action = actionCreateFolder;
  1812. if (autoUploadDirectory)
  1813. metadataNet.options = @"folderAutoUpload";
  1814. metadataNet.fileName = fileNameFolder;
  1815. metadataNet.selector = selectorCreateFolder;
  1816. metadataNet.selectorPost = selectorReadFolderForced;
  1817. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1818. if (!autoUploadDirectory)
  1819. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1820. }
  1821. - (void)createFolderEncrypted:(NSString *)fileNameFolder
  1822. {
  1823. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1824. NSString *fileNamePlist;
  1825. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1826. if (![fileNameFolder length]) return;
  1827. NSString *title = [AESCrypt encrypt:fileNameFolder password:[[CCCrypto sharedManager] getKeyPasscode:[CCUtility getUUID]]];
  1828. fileNamePlist = [[CCCrypto sharedManager] createFilenameEncryptor:fileNameFolder uuid:[CCUtility getUUID]];
  1829. [[CCCrypto sharedManager] createFilePlist:[NSTemporaryDirectory() stringByAppendingString:fileNamePlist] title:title len:0 directory:true uuid:[CCUtility getUUID] nameCurrentDevice:[CCUtility getNameCurrentDevice] icon:@""];
  1830. // Create folder
  1831. metadataNet.action = actionCreateFolder;
  1832. metadataNet.fileName = fileNamePlist;
  1833. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1834. metadataNet.selector = selectorCreateFolder;
  1835. metadataNet.serverUrl = _serverUrl;
  1836. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1837. // upload plist file
  1838. metadataNet.action = actionUploadOnlyPlist;
  1839. metadataNet.fileName = [fileNamePlist stringByAppendingString:@".plist"];
  1840. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1841. metadataNet.selectorPost = selectorReadFolderForced;
  1842. metadataNet.serverUrl = _serverUrl;
  1843. metadataNet.session = k_upload_session_foreground;
  1844. metadataNet.taskStatus = k_taskStatusResume;
  1845. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1846. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1847. }
  1848. - (void)createFolderAutoUpload
  1849. {
  1850. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  1851. [self createFolder:autoUploadFileName autoUploadDirectory:YES];
  1852. }
  1853. #pragma --------------------------------------------------------------------------------------------
  1854. #pragma mark ===== Encrypted / Decrypted Folder =====
  1855. #pragma --------------------------------------------------------------------------------------------
  1856. - (void)encyptedDecryptedFolder
  1857. {
  1858. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  1859. if (_metadata.cryptated) {
  1860. // DECRYPTED
  1861. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1862. //-------------------------- RENAME -------------------------------------------//
  1863. metadataNet.action = actionMoveFileOrFolder;
  1864. metadataNet.fileID = _metadata.fileID;
  1865. metadataNet.fileName = _metadata.fileNameData;
  1866. metadataNet.fileNameTo = _metadata.fileNamePrint;
  1867. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1868. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1869. metadataNet.selector = selectorRename;
  1870. metadataNet.serverUrl = serverUrl;
  1871. metadataNet.serverUrlTo = serverUrl;
  1872. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1873. //-------------------------- DELETE -------------------------------------------//
  1874. metadataNet.action = actionDeleteFileDirectory;
  1875. metadataNet.fileID = _metadata.fileID;
  1876. metadataNet.fileName = _metadata.fileName;
  1877. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1878. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1879. metadataNet.selector = selectorDeletePlist;
  1880. metadataNet.selectorPost = selectorReadFolderForced;
  1881. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1882. } else {
  1883. // ENCRYPTED
  1884. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1885. // Create File Plist
  1886. NSString *fileNameCrypto = [[CCCrypto sharedManager] createFileDirectoryPlist:_metadata];
  1887. //-------------------------- RENAME -------------------------------------------//
  1888. metadataNet.action = actionMoveFileOrFolder;
  1889. metadataNet.fileID = _metadata.fileID;
  1890. metadataNet.fileName = _metadata.fileName;
  1891. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1892. metadataNet.fileNameTo = fileNameCrypto;
  1893. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1894. metadataNet.selector = selectorRename;
  1895. metadataNet.serverUrl = serverUrl;
  1896. metadataNet.serverUrlTo = serverUrl;
  1897. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1898. //-------------------------- UPLOAD -------------------------------------------//
  1899. metadataNet.action = actionUploadOnlyPlist;
  1900. metadataNet.fileName = [fileNameCrypto stringByAppendingString:@".plist"];
  1901. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1902. metadataNet.selectorPost = selectorReadFolderForced;
  1903. metadataNet.serverUrl = serverUrl;
  1904. metadataNet.session = k_upload_session_foreground;
  1905. metadataNet.taskStatus = k_taskStatusResume;
  1906. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1907. }
  1908. }
  1909. #pragma --------------------------------------------------------------------------------------------
  1910. #pragma mark ===== Encrypted/Decrypted File =====
  1911. #pragma --------------------------------------------------------------------------------------------
  1912. - (void)encryptedSelectedFiles
  1913. {
  1914. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1915. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1916. for (tableMetadata *metadata in selectedMetadatas) {
  1917. if (metadata.cryptated == NO && metadata.directory == NO)
  1918. [metadatas addObject:metadata];
  1919. }
  1920. if ([metadatas count] > 0) {
  1921. NSLog(@"[LOG] Start encrypted selected files ...");
  1922. for (tableMetadata* metadata in metadatas) {
  1923. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1924. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorEncryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1925. }
  1926. }
  1927. [self tableViewSelect:NO];
  1928. }
  1929. - (void)decryptedSelectedFiles
  1930. {
  1931. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1932. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1933. for (tableMetadata *metadata in selectedMetadatas) {
  1934. if (metadata.cryptated == YES && metadata.directory == NO && [metadata.model length] == 0)
  1935. [metadatas addObject:metadata];
  1936. }
  1937. if ([metadatas count] > 0) {
  1938. NSLog(@"[LOG] Start decrypted selected files ...");
  1939. for (tableMetadata* metadata in metadatas) {
  1940. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1941. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorDecryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1942. }
  1943. }
  1944. [self tableViewSelect:NO];
  1945. }
  1946. - (void)cmdEncryptedDecryptedFile
  1947. {
  1948. NSString *selector;
  1949. if (_metadata.cryptated == YES) selector = selectorDecryptFile;
  1950. if (_metadata.cryptated == NO) selector = selectorEncryptFile;
  1951. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  1952. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  1953. }
  1954. - (void)encryptedFile:(tableMetadata *)metadata
  1955. {
  1956. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1957. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1958. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1959. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1960. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1961. dispatch_async(dispatch_get_main_queue(), ^{
  1962. [[CCNetworking sharedNetworking] uploadFile:metadata.fileName serverUrl:serverUrl cryptated:YES onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  1963. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1964. });
  1965. } else {
  1966. [app messageNotification:@"_encrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1967. }
  1968. }
  1969. - (void)decryptedFile:(tableMetadata *)metadata
  1970. {
  1971. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1972. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1973. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1974. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1975. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1976. dispatch_async(dispatch_get_main_queue(), ^{
  1977. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:serverUrl cryptated:NO onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  1978. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1979. });
  1980. } else {
  1981. [app messageNotification:@"_decrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1982. }
  1983. }
  1984. #pragma --------------------------------------------------------------------------------------------
  1985. #pragma mark ===== Progress & Task Button =====
  1986. #pragma --------------------------------------------------------------------------------------------
  1987. - (void)triggerProgressTask:(NSNotification *)notification
  1988. {
  1989. NSDictionary *dict = notification.userInfo;
  1990. NSString *fileID = [dict valueForKey:@"fileID"];
  1991. NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  1992. BOOL cryptated = [[dict valueForKey:@"cryptated"] boolValue];
  1993. float progress = [[dict valueForKey:@"progress"] floatValue];
  1994. // Check
  1995. if (!fileID)
  1996. return;
  1997. [app.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  1998. if (![serverUrl isEqualToString:_serverUrl])
  1999. return;
  2000. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  2001. if (indexPath) {
  2002. CCTransfersCell *cell = (CCTransfersCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  2003. if (cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  2004. else cell.progressView.progressTintColor = [UIColor blackColor];
  2005. cell.progressView.hidden = NO;
  2006. [cell.progressView setProgress:progress];
  2007. }
  2008. if (progress == 0)
  2009. [self.navigationController cancelCCProgress];
  2010. else
  2011. [self.navigationController setCCProgressPercentage:progress*100 andTintColor: [NCBrandColor sharedInstance].navigationBarProgress];
  2012. }
  2013. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  2014. {
  2015. UITouch * touch = [[event allTouches] anyObject];
  2016. CGPoint location = [touch locationInView:self.tableView];
  2017. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2018. if (indexPath) {
  2019. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2020. if (metadata)
  2021. [self reloadTaskButton:metadata];
  2022. }
  2023. }
  2024. - (void)reloadTaskButton:(tableMetadata *)metadata
  2025. {
  2026. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2027. __block NSURLSessionTask *findTask;
  2028. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2029. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2030. NSString *fileID = metadata.fileID;
  2031. // DOWNLOAD
  2032. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  2033. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2034. for (NSURLSessionUploadTask *task in downloadTasks)
  2035. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2036. findTask = task;
  2037. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  2038. [task cancel];
  2039. }
  2040. if (!findTask) {
  2041. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  2042. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2043. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2044. }
  2045. }];
  2046. }
  2047. // UPLOAD
  2048. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2049. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2050. for (NSURLSessionUploadTask *task in uploadTasks)
  2051. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2052. findTask = task;
  2053. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  2054. [task cancel];
  2055. }
  2056. if (!findTask) {
  2057. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  2058. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2059. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2060. }
  2061. }];
  2062. }
  2063. }
  2064. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  2065. {
  2066. UITouch * touch = [[event allTouches] anyObject];
  2067. CGPoint location = [touch locationInView:self.tableView];
  2068. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2069. if (indexPath) {
  2070. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2071. if (metadata)
  2072. [self cancelTaskButton:metadata reloadTable:YES];
  2073. }
  2074. }
  2075. - (void)cancelTaskButton:(tableMetadata *)metadata reloadTable:(BOOL)reloadTable
  2076. {
  2077. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2078. __block NSURLSessionTask *findTask;
  2079. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2080. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2081. NSString *fileID = metadata.fileID;
  2082. // DOWNLOAD
  2083. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  2084. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2085. for (NSURLSessionTask *task in downloadTasks)
  2086. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2087. findTask = task;
  2088. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  2089. [task cancel];
  2090. }
  2091. if (!findTask) {
  2092. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  2093. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2094. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2095. }
  2096. }];
  2097. }
  2098. // UPLOAD
  2099. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2100. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2101. for (NSURLSessionUploadTask *task in uploadTasks)
  2102. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2103. findTask = task;
  2104. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  2105. [task cancel];
  2106. }
  2107. if (!findTask) {
  2108. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  2109. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2110. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2111. }
  2112. }];
  2113. }
  2114. }
  2115. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  2116. {
  2117. UITouch * touch = [[event allTouches] anyObject];
  2118. CGPoint location = [touch locationInView:self.tableView];
  2119. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2120. if (indexPath) {
  2121. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2122. if (metadata)
  2123. [self stopTaskButton:metadata];
  2124. }
  2125. }
  2126. - (void)stopTaskButton:(tableMetadata *)metadata
  2127. {
  2128. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2129. __block NSURLSessionTask *findTask;
  2130. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2131. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2132. NSString *fileID = metadata.fileID;
  2133. // UPLOAD
  2134. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2135. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2136. for (NSURLSessionUploadTask *task in uploadTasks)
  2137. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2138. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  2139. findTask = task;
  2140. [task cancel];
  2141. }
  2142. if (!findTask) {
  2143. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  2144. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2145. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2146. }
  2147. }];
  2148. }
  2149. }
  2150. #pragma --------------------------------------------------------------------------------------------
  2151. #pragma mark ===== Shared =====
  2152. #pragma --------------------------------------------------------------------------------------------
  2153. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  2154. {
  2155. [_hud hideHud];
  2156. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2157. // change account ?
  2158. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  2159. if([record.account isEqualToString:metadataNet.account] == NO)
  2160. return;
  2161. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items activeUrl:appDelegate.activeUrl];
  2162. if (result) {
  2163. appDelegate.sharesLink = result[0];
  2164. appDelegate.sharesUserAndGroup = result[1];
  2165. }
  2166. // Notify Shares View
  2167. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"SharesReloadDatasource" object:nil userInfo:nil];
  2168. if (openWindow) {
  2169. if (_shareOC) {
  2170. [_shareOC reloadData];
  2171. } else {
  2172. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2173. // Apriamo la view
  2174. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  2175. _shareOC.delegate = self;
  2176. _shareOC.metadata = metadata;
  2177. _shareOC.serverUrl = metadataNet.serverUrl;
  2178. _shareOC.shareLink = [app.sharesLink objectForKey:metadata.fileID];
  2179. _shareOC.shareUserAndGroup = [app.sharesUserAndGroup objectForKey:metadata.fileID];
  2180. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  2181. [self presentViewController:_shareOC animated:YES completion:nil];
  2182. }
  2183. }
  2184. [self tableViewReload];
  2185. }
  2186. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2187. {
  2188. [_hud hideHud];
  2189. [app messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2190. if (_shareOC)
  2191. [_shareOC reloadData];
  2192. [self tableViewReload];
  2193. if (errorCode == 401)
  2194. [self changePasswordAccount];
  2195. }
  2196. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  2197. {
  2198. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2199. metadataNet.action = actionShare;
  2200. metadataNet.fileID = metadata.fileID;
  2201. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2202. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2203. metadataNet.password = password;
  2204. metadataNet.selector = selectorShare;
  2205. metadataNet.serverUrl = serverUrl;
  2206. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2207. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2208. }
  2209. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  2210. {
  2211. [_hud hideHud];
  2212. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2213. // rimuoviamo la condivisione da db
  2214. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup];
  2215. if (result) {
  2216. appDelegate.sharesLink = result[0];
  2217. appDelegate.sharesUserAndGroup = result[1];
  2218. }
  2219. if (_shareOC)
  2220. [_shareOC reloadData];
  2221. [self tableViewReload];
  2222. }
  2223. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  2224. {
  2225. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2226. metadataNet.action = actionUnShare;
  2227. metadataNet.fileID = metadata.fileID;
  2228. metadataNet.fileName = metadata.fileName;
  2229. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2230. metadataNet.selector = selectorUnshare;
  2231. metadataNet.serverUrl = serverUrl;
  2232. metadataNet.share = share;
  2233. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2234. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2235. }
  2236. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  2237. {
  2238. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2239. metadataNet.action = actionUpdateShare;
  2240. metadataNet.fileID = metadata.fileID;
  2241. metadataNet.expirationTime = expirationTime;
  2242. metadataNet.password = password;
  2243. metadataNet.selector = selectorUpdateShare;
  2244. metadataNet.serverUrl = serverUrl;
  2245. metadataNet.share = share;
  2246. metadataNet.sharePermission = permission;
  2247. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2248. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2249. }
  2250. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  2251. {
  2252. [_hud hideHud];
  2253. if (_shareOC)
  2254. [_shareOC reloadUserAndGroup:items];
  2255. }
  2256. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2257. {
  2258. [_hud hideHud];
  2259. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2260. }
  2261. - (void)getUserAndGroup:(NSString *)find
  2262. {
  2263. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2264. metadataNet.action = actionGetUserAndGroup;
  2265. metadataNet.options = find;
  2266. metadataNet.selector = selectorGetUserAndGroup;
  2267. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2268. [_hud visibleIndeterminateHud];
  2269. }
  2270. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  2271. {
  2272. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2273. metadataNet.action = actionShareWith;
  2274. metadataNet.fileID = metadata.fileID;
  2275. metadataNet.directoryID = directoryID;
  2276. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2277. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2278. metadataNet.serverUrl = serverUrl;
  2279. metadataNet.selector = selectorShare;
  2280. metadataNet.share = user;
  2281. metadataNet.shareeType = shareeType;
  2282. metadataNet.sharePermission = permission;
  2283. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2284. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2285. }
  2286. - (void)openWindowShare:(tableMetadata *)metadata
  2287. {
  2288. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2289. metadataNet.action = actionReadShareServer;
  2290. metadataNet.fileID = metadata.fileID;
  2291. metadataNet.fileName = metadata.fileName;
  2292. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2293. metadataNet.selector = selectorOpenWindowShare;
  2294. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2295. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2296. [_hud visibleIndeterminateHud];
  2297. }
  2298. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  2299. {
  2300. CGPoint location = [tapGesture locationInView:self.tableView];
  2301. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2302. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2303. if (metadata)
  2304. [self openWindowShare:metadata];
  2305. }
  2306. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2307. {
  2308. CGPoint location = [tapGesture locationInView:self.tableView];
  2309. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2310. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2311. if (metadata) {
  2312. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2313. vc.metadata = metadata;
  2314. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2315. [self presentViewController:vc animated:YES completion:nil];
  2316. }
  2317. }
  2318. #pragma --------------------------------------------------------------------------------------------
  2319. #pragma mark ===== Favorite =====
  2320. #pragma --------------------------------------------------------------------------------------------
  2321. - (void)settingFavoriteSuccess:(CCMetadataNet *)metadataNet
  2322. {
  2323. _dateReadDataSource = nil;
  2324. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithFileID:metadataNet.fileID favorite:[metadataNet.options boolValue]];
  2325. if (_isSearchMode)
  2326. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  2327. else
  2328. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  2329. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2330. if (metadata.directory && metadata.favorite) {
  2331. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileNameData];
  2332. [app.activeFavorites addFavoriteFolder:dir];
  2333. }
  2334. }
  2335. - (void)settingFavoriteFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2336. {
  2337. }
  2338. - (void)addFavorite:(tableMetadata *)metadata
  2339. {
  2340. if (metadata.directory) {
  2341. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  2342. } else {
  2343. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2344. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddFavorite selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2345. }
  2346. }
  2347. - (void)removeFavorite:(tableMetadata *)metadata
  2348. {
  2349. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  2350. }
  2351. #pragma --------------------------------------------------------------------------------------------
  2352. #pragma mark ===== Local =====
  2353. #pragma --------------------------------------------------------------------------------------------
  2354. - (void)addLocal:(tableMetadata *)metadata
  2355. {
  2356. if (metadata.errorPasscode || !metadata.uuid) return;
  2357. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2358. if ([metadata.type isEqualToString: k_metadataType_file])
  2359. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddLocal selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2360. if ([metadata.type isEqualToString: k_metadataType_template]) {
  2361. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileName]];
  2362. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  2363. }
  2364. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2365. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2366. }
  2367. #pragma --------------------------------------------------------------------------------------------
  2368. #pragma mark ===== Open in... =====
  2369. #pragma --------------------------------------------------------------------------------------------
  2370. - (void)openIn:(tableMetadata *)metadata
  2371. {
  2372. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2373. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2374. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2375. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2376. }
  2377. #pragma --------------------------------------------------------------------------------------------
  2378. #pragma mark ===== Remove Local File =====
  2379. #pragma --------------------------------------------------------------------------------------------
  2380. - (void)removeLocalFile:(tableMetadata *)metadata
  2381. {
  2382. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2383. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  2384. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  2385. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:nil];
  2386. }
  2387. #pragma --------------------------------------------------------------------------------------------
  2388. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2389. #pragma --------------------------------------------------------------------------------------------
  2390. - (void)orderTable:(NSString *)order
  2391. {
  2392. [CCUtility setOrderSettings:order];
  2393. // Clear data-read of DataSource
  2394. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2395. }
  2396. - (void)ascendingTable:(BOOL)ascending
  2397. {
  2398. [CCUtility setAscendingSettings:ascending];
  2399. // Clear data-read of DataSource
  2400. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2401. }
  2402. - (void)directoryOnTop:(BOOL)directoryOnTop
  2403. {
  2404. [CCUtility setDirectoryOnTop:directoryOnTop];
  2405. // Clear data-read of DataSource
  2406. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2407. }
  2408. - (void)tableGroupBy:(NSString *)groupBy
  2409. {
  2410. [CCUtility setGroupBySettings:groupBy];
  2411. // Clear data-read of DataSource
  2412. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2413. }
  2414. #pragma --------------------------------------------------------------------------------------------
  2415. #pragma mark ==== Menu LOGO ====
  2416. #pragma --------------------------------------------------------------------------------------------
  2417. - (void)menuLogo
  2418. {
  2419. if (app.reSelectMenu.isOpen || app.reMainMenu.isOpen)
  2420. return;
  2421. // Brand
  2422. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  2423. return;
  2424. if ([app.netQueue operationCount] > 0 || [app.netQueueDownload operationCount] > 0 || [app.netQueueDownloadWWan operationCount] > 0 || [app.netQueueUpload operationCount] > 0 || [app.netQueueUploadWWan operationCount] > 0 || [[NCManageDatabase sharedInstance] countAutoUploadWithSession:nil] > 0) {
  2425. [app messageNotification:@"_transfers_in_queue_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  2426. return;
  2427. }
  2428. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  2429. NSMutableArray *menuArray = [NSMutableArray new];
  2430. for (NSString *account in listAccount) {
  2431. if ([account isEqualToString:app.activeAccount]) continue;
  2432. CCMenuItem *item = [[CCMenuItem alloc] init];
  2433. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2434. item.argument = account;
  2435. item.image = [UIImage imageNamed:@"menuLogoUser"];
  2436. item.target = self;
  2437. item.action = @selector(changeDefaultAccount:);
  2438. [menuArray addObject:item];
  2439. }
  2440. if ([menuArray count] == 0)
  2441. return;
  2442. OptionalConfiguration options;
  2443. Color textColor, backgroundColor;
  2444. textColor.R = 0;
  2445. textColor.G = 0;
  2446. textColor.B = 0;
  2447. backgroundColor.R = 1;
  2448. backgroundColor.G = 1;
  2449. backgroundColor.B = 1;
  2450. NSInteger originY = 60;
  2451. options.arrowSize = 9;
  2452. options.marginXSpacing = 7;
  2453. options.marginYSpacing = 10;
  2454. options.intervalSpacing = 20;
  2455. options.menuCornerRadius = 6.5;
  2456. options.maskToBackground = NO;
  2457. options.shadowOfMenu = YES;
  2458. options.hasSeperatorLine = YES;
  2459. options.seperatorLineHasInsets = YES;
  2460. options.textColor = textColor;
  2461. options.menuBackgroundColor = backgroundColor;
  2462. CGRect rect = self.view.frame;
  2463. rect.origin.y = rect.origin.y + originY;
  2464. rect.size.height = rect.size.height - originY;
  2465. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2466. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2467. }
  2468. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2469. {
  2470. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  2471. // STOP, erase all in queue networking
  2472. [app cancelAllOperations];
  2473. [[CCNetworking sharedNetworking] settingSessionsDownload:YES upload:YES taskStatus:k_taskStatusCancel activeAccount:app.activeAccount activeUser:app.activeUser activeUrl:app.activeUrl];
  2474. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2475. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  2476. if (tableAccount)
  2477. [app settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activePassword:tableAccount.password];
  2478. // go to home sweet home
  2479. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil];
  2480. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  2481. });
  2482. }
  2483. #pragma --------------------------------------------------------------------------------------------
  2484. #pragma mark ==== ReMenu ====
  2485. #pragma --------------------------------------------------------------------------------------------
  2486. - (void)createReMenuBackgroundView:(REMenu *)menu
  2487. {
  2488. __block CGFloat navigationBarH = self.navigationController.navigationBar.frame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height;
  2489. _reMenuBackgroundView.frame = CGRectMake(0, navigationBarH, self.view.frame.size.width, self.view.frame.size.height);
  2490. [UIView animateWithDuration:0.2 animations:^{
  2491. float height = (self.view.frame.size.height + navigationBarH) - (menu.menuView.frame.size.height - self.navigationController.navigationBar.frame.size.height + 3);
  2492. if (height < self.tabBarController.tabBar.frame.size.height)
  2493. height = self.tabBarController.tabBar.frame.size.height;
  2494. _reMenuBackgroundView.frame = CGRectMake(0, self.view.frame.size.height + navigationBarH, self.view.frame.size.width, - height);
  2495. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2496. }];
  2497. }
  2498. - (void)createReMainMenu
  2499. {
  2500. NSString *ordinamento;
  2501. NSString *groupBy = _directoryGroupBy;
  2502. __block NSString *nuovoOrdinamento;
  2503. NSString *titoloNuovo, *titoloAttuale;
  2504. BOOL ascendente;
  2505. __block BOOL nuovoAscendente;
  2506. UIImage *image;
  2507. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2508. app.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"seleziona"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2509. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2510. [self tableViewSelect:YES];
  2511. }
  2512. }];
  2513. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2514. ordinamento = _directoryOrder;
  2515. if ([ordinamento isEqualToString:@"fileName"]) {
  2516. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdeyByDate"] color:[NCBrandColor sharedInstance].brand];
  2517. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2518. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2519. nuovoOrdinamento = @"date";
  2520. }
  2521. if ([ordinamento isEqualToString:@"date"]) {
  2522. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrderByFileName"] color:[NCBrandColor sharedInstance].brand];
  2523. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2524. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2525. nuovoOrdinamento = @"fileName";
  2526. }
  2527. app.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2528. [self orderTable:nuovoOrdinamento];
  2529. }];
  2530. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2531. ascendente = [CCUtility getAscendingSettings];
  2532. if (ascendente) {
  2533. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoDiscendente"] color:[NCBrandColor sharedInstance].brand];
  2534. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2535. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2536. nuovoAscendente = false;
  2537. }
  2538. if (!ascendente) {
  2539. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoAscendente"] color:[NCBrandColor sharedInstance].brand];
  2540. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2541. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2542. nuovoAscendente = true;
  2543. }
  2544. app.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2545. [self ascendingTable:nuovoAscendente];
  2546. }];
  2547. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2548. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2549. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2550. app.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2551. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2552. else [self tableGroupBy:@"alphabetic"];
  2553. }];
  2554. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2555. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2556. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2557. app.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByTypeFile"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2558. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2559. else [self tableGroupBy:@"typefile"];
  2560. }];
  2561. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2562. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2563. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2564. app.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2565. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2566. else [self tableGroupBy:@"date"];
  2567. }];
  2568. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2569. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2570. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2571. app.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"menuDirectoryOnTop"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2572. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2573. else [self directoryOnTop:YES];
  2574. }];
  2575. // REMENU --------------------------------------------------------------------------------------------------------------
  2576. app.reMainMenu = [[REMenu alloc] initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2577. app.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2578. app.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2579. app.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2580. app.reMainMenu.waitUntilAnimationIsComplete = NO;
  2581. app.reMainMenu.separatorHeight = 0.5;
  2582. app.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2583. app.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2584. app.reMainMenu.textColor = [UIColor blackColor];
  2585. app.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2586. app.reMainMenu.textShadowColor = nil;
  2587. app.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2588. app.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2589. app.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2590. app.reMainMenu.highlightedSeparatorColor = nil;
  2591. app.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2592. app.reMainMenu.highlightedTextShadowColor = nil;
  2593. app.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2594. app.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2595. app.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2596. app.reMainMenu.subtitleTextShadowColor = nil;
  2597. app.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2598. app.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2599. app.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2600. app.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2601. app.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2602. app.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2603. app.reMainMenu.borderWidth = 0.3;
  2604. app.reMainMenu.borderColor = [UIColor lightGrayColor];
  2605. app.reMainMenu.animationDuration = 0.2;
  2606. app.reMainMenu.closeAnimationDuration = 0.2;
  2607. app.reMainMenu.bounce = NO;
  2608. [app.reMainMenu setClosePreparationBlock:^{
  2609. // Backgroun reMenu (Gesture)
  2610. [_reMenuBackgroundView removeFromSuperview];
  2611. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2612. }];
  2613. }
  2614. - (void)toggleReMainMenu
  2615. {
  2616. if (app.reMainMenu.isOpen) {
  2617. [app.reMainMenu close];
  2618. } else {
  2619. [self createReMainMenu];
  2620. [app.reMainMenu showFromNavigationController:self.navigationController];
  2621. // Backgroun reMenu & (Gesture)
  2622. [self createReMenuBackgroundView:app.reMainMenu];
  2623. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2624. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2625. }
  2626. }
  2627. - (void)createReSelectMenu
  2628. {
  2629. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2630. app.deleteItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"deleteSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2631. [self deleteSelectionFile];
  2632. }];
  2633. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2634. app.moveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_move_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"moveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2635. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2636. }];
  2637. if (app.isCryptoCloudMode) {
  2638. // ITEM ENCRYPTED ------------------------------------------------------------------------------------------------------
  2639. app.encryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_encrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"encryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2640. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil];
  2641. }];
  2642. // ITEM DECRYPTED ----------------------------------------------------------------------------------------------------
  2643. app.decryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_decrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"decryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2644. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil];
  2645. }];
  2646. }
  2647. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2648. app.downloadItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_download_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"downloadSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2649. [self downloadSelectedFiles];
  2650. }];
  2651. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2652. app.saveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_save_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"saveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2653. [self saveSelectedFiles];
  2654. }];
  2655. // REMENU --------------------------------------------------------------------------------------------------------------
  2656. if (app.isCryptoCloudMode) {
  2657. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2658. } else {
  2659. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2660. }
  2661. app.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2662. app.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2663. app.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2664. app.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2665. app.reSelectMenu.separatorHeight = 0.5;
  2666. app.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2667. app.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2668. app.reSelectMenu.textColor = [UIColor blackColor];
  2669. app.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2670. app.reSelectMenu.textShadowColor = nil;
  2671. app.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2672. app.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2673. app.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2674. app.reSelectMenu.highlightedSeparatorColor = nil;
  2675. app.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2676. app.reSelectMenu.highlightedTextShadowColor = nil;
  2677. app.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2678. app.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2679. app.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2680. app.reSelectMenu.subtitleTextShadowColor = nil;
  2681. app.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2682. app.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2683. app.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2684. app.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2685. app.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2686. app.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2687. app.reSelectMenu.borderWidth = 0.3;
  2688. app.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2689. app.reSelectMenu.closeAnimationDuration = 0.2;
  2690. app.reSelectMenu.animationDuration = 0.2;
  2691. app.reSelectMenu.bounce = NO;
  2692. [app.reSelectMenu setClosePreparationBlock:^{
  2693. // Backgroun reMenu (Gesture)
  2694. [_reMenuBackgroundView removeFromSuperview];
  2695. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2696. }];
  2697. }
  2698. - (void)toggleReSelectMenu
  2699. {
  2700. if (app.reSelectMenu.isOpen) {
  2701. [app.reSelectMenu close];
  2702. } else {
  2703. [self createReSelectMenu];
  2704. [app.reSelectMenu showFromNavigationController:self.navigationController];
  2705. // Backgroun reMenu & (Gesture)
  2706. [self createReMenuBackgroundView:app.reSelectMenu];
  2707. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2708. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2709. }
  2710. }
  2711. #pragma --------------------------------------------------------------------------------------------
  2712. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2713. #pragma --------------------------------------------------------------------------------------------
  2714. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2715. {
  2716. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2717. UITableView *tableView = (UITableView*)self.view;
  2718. CGPoint touchPoint = [recognizer locationInView:self.view];
  2719. NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPoint];
  2720. if (indexPath)
  2721. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2722. else
  2723. _metadata = nil;
  2724. [self becomeFirstResponder];
  2725. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2726. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2727. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2728. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2729. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2730. UIMenuItem *pasteFileEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_encrypted_", nil) action:@selector(pasteFileEncrypted:)];
  2731. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2732. UIMenuItem *pasteFilesEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_encrypted_", nil) action:@selector(pasteFilesEncrypted:)];
  2733. if (app.isCryptoCloudMode)
  2734. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, pasteFileEncryptedItem, pasteFilesEncryptedItem, nil]];
  2735. else
  2736. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2737. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:tableView];
  2738. [menuController setMenuVisible:YES animated:YES];
  2739. }
  2740. }
  2741. - (BOOL)canBecomeFirstResponder
  2742. {
  2743. return YES;
  2744. }
  2745. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2746. {
  2747. // For copy file, copy files, Open in ... :
  2748. //
  2749. // NO Directory
  2750. // NO Error Passcode
  2751. // NO In Session mode (download/upload)
  2752. // NO Template
  2753. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2754. if (_isSelectedMode == NO && _metadata && !_metadata.directory && !_metadata.errorPasscode && [_metadata.session length] == 0 && ![_metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2755. // NO Cryptated with Title lenght = 0
  2756. if (!_metadata.cryptated || (_metadata.cryptated && _metadata.title.length > 0))
  2757. return YES;
  2758. }
  2759. return NO;
  2760. }
  2761. if (@selector(copyFiles:) == action) {
  2762. if (_isSelectedMode) {
  2763. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2764. for (tableMetadata *metadata in selectedMetadatas) {
  2765. if (!metadata.directory && !metadata.errorPasscode && metadata.session.length == 0 && ![metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2766. // NO Cryptated with Title lenght = 0
  2767. if (!metadata.cryptated || (metadata.cryptated && metadata.title.length > 0))
  2768. return YES;
  2769. }
  2770. }
  2771. }
  2772. return NO;
  2773. }
  2774. if (@selector(pasteFile:) == action || @selector(pasteFileEncrypted:) == action) {
  2775. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2776. NSArray *items = [pasteboard items];
  2777. if ([items count] == 1) {
  2778. // Value : (NSData) fileID
  2779. NSDictionary *dic = [items objectAtIndex:0];
  2780. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2781. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2782. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2783. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2784. if (directoryUser) {
  2785. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2786. return YES;
  2787. }
  2788. return NO;
  2789. } else return NO;
  2790. }
  2791. if (@selector(pasteFiles:) == action || @selector(pasteFilesEncrypted:) == action) {
  2792. BOOL isValid = NO;
  2793. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2794. NSArray *items = [pasteboard items];
  2795. if ([items count] <= 1) return NO;
  2796. for (NSDictionary *dic in items) {
  2797. // Value : (NSData) fileID
  2798. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2799. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2800. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2801. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2802. if (directoryUser) {
  2803. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2804. isValid = YES;
  2805. }
  2806. }
  2807. return isValid;
  2808. }
  2809. return NO;
  2810. }
  2811. /************************************ COPY ************************************/
  2812. - (void)copyFile:(id)sender
  2813. {
  2814. // Remove all item
  2815. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2816. pasteboard.items = [[NSArray alloc] init];
  2817. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser,_metadata.fileID]]) {
  2818. [self copyFileToPasteboard:_metadata];
  2819. } else {
  2820. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2821. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2822. }
  2823. }
  2824. - (void)copyFiles:(id)sender
  2825. {
  2826. // Remove all item
  2827. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2828. pasteboard.items = [[NSArray alloc] init];
  2829. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2830. for (tableMetadata *metadata in selectedMetadatas) {
  2831. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]]) {
  2832. [self copyFileToPasteboard:metadata];
  2833. } else {
  2834. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2835. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2836. }
  2837. }
  2838. [self tableViewSelect:NO];
  2839. }
  2840. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2841. {
  2842. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2843. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2844. // Value : (NSData) fileID
  2845. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.fileID], k_metadataKeyedUnarchiver,nil];
  2846. [items addObject:item];
  2847. [pasteboard setItems:items];
  2848. }
  2849. /************************************ OPEN IN ... ************************************/
  2850. - (void)openinFile:(id)sender
  2851. {
  2852. [self openIn:_metadata];
  2853. }
  2854. /************************************ PASTE ************************************/
  2855. - (void)pasteFile:(id)sender
  2856. {
  2857. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2858. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2859. }
  2860. - (void)pasteFileEncrypted:(id)sender
  2861. {
  2862. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2863. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2864. }
  2865. - (void)pasteFiles:(id)sender
  2866. {
  2867. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2868. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2869. }
  2870. - (void)pasteFilesEncrypted:(id)sender
  2871. {
  2872. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2873. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2874. }
  2875. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2876. {
  2877. for (NSDictionary *dic in items) {
  2878. // Value : (NSData) fileID
  2879. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2880. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2881. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2882. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2883. if (!metadata || !account) return;
  2884. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2885. if (directoryUser) {
  2886. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2887. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint]];
  2888. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:_serverUrl cryptated:cryptated onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  2889. }
  2890. }
  2891. }
  2892. }
  2893. #pragma --------------------------------------------------------------------------------------------
  2894. #pragma mark ===== Lock Passcode =====
  2895. #pragma --------------------------------------------------------------------------------------------
  2896. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2897. {
  2898. return _failedAttempts;
  2899. }
  2900. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2901. {
  2902. return _lockUntilDate;
  2903. }
  2904. - (void)passcodeViewCloseButtonPressed:(id)sender
  2905. {
  2906. [self dismissViewControllerAnimated:YES completion:nil];
  2907. }
  2908. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2909. {
  2910. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2911. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2912. _lockUntilDate = nil;
  2913. _failedAttempts = 0;
  2914. aResultHandler(YES);
  2915. } else aResultHandler(NO);
  2916. } else aResultHandler(YES);
  2917. }
  2918. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2919. {
  2920. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2921. switch (aViewController.type) {
  2922. case BKPasscodeViewControllerCheckPasscodeType: {
  2923. if (aViewController.fromType == CCBKPasscodeFromPasscode) {
  2924. // verifichiamo se il passcode è corretto per il seguente file -> UUID
  2925. if ([[CCCrypto sharedManager] verifyPasscode:aPasscode uuid:_metadata.uuid text:_metadata.title]) {
  2926. // scriviamo il passcode
  2927. [CCUtility setKeyChainPasscodeForUUID:_metadata.uuid conPasscode:aPasscode];
  2928. [self readFolderWithForced:YES serverUrl:_serverUrl];
  2929. } else {
  2930. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2931. [alertView show];
  2932. }
  2933. }
  2934. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2935. // possiamo procedere alla prossima directory
  2936. [self performSegueDirectoryWithControlPasscode:false];
  2937. // avviamo la sessione Passcode Lock con now
  2938. app.sessionePasscodeLock = [NSDate date];
  2939. }
  2940. // disattivazione lock cartella
  2941. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2942. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2943. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2944. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO]) {
  2945. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2946. }
  2947. [self tableViewReload];
  2948. }
  2949. }
  2950. break;
  2951. default:
  2952. break;
  2953. }
  2954. }
  2955. - (void)comandoLockPassword
  2956. {
  2957. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2958. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2959. // se non è abilitato il Lock Passcode esci
  2960. if ([[CCUtility getBlockCode] length] == 0) {
  2961. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2962. [alertView show];
  2963. return;
  2964. }
  2965. // se è richiesta la disattivazione si chiede la password
  2966. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  2967. if (directory.lock) {
  2968. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2969. viewController.delegate = self;
  2970. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2971. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2972. viewController.inputViewTitlePassword = YES;
  2973. if ([CCUtility getSimplyBlockCode]) {
  2974. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2975. viewController.passcodeInputView.maximumLength = 6;
  2976. } else {
  2977. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2978. viewController.passcodeInputView.maximumLength = 64;
  2979. }
  2980. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2981. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2982. viewController.touchIDManager = touchIDManager;
  2983. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2984. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2985. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  2986. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2987. [self presentViewController:navigationController animated:YES completion:nil];
  2988. return;
  2989. }
  2990. // ---------------- ACTIVATE PASSWORD
  2991. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES]) {
  2992. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2993. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2994. } else {
  2995. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2996. }
  2997. }
  2998. #pragma mark -
  2999. #pragma --------------------------------------------------------------------------------------------
  3000. #pragma mark ===== Swipe Tablet -> menu =====
  3001. #pragma --------------------------------------------------------------------------------------------
  3002. // more
  3003. - (NSString *)tableView:(UITableView *)tableView titleForSwipeAccessoryButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
  3004. return NSLocalizedString(@"_more_", nil);
  3005. }
  3006. - (void)tableView:(UITableView *)tableView swipeAccessoryButtonPushedForRowAtIndexPath:(NSIndexPath *)indexPath
  3007. {
  3008. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3009. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3010. NSString *titoloCriptaDecripta, *titoloLock, *titleFavorite;
  3011. if (_metadata.cryptated) titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_decrypt_", nil)];
  3012. else titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_encrypt_", nil)];
  3013. if (_metadata.favorite) {
  3014. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  3015. } else {
  3016. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  3017. }
  3018. if (_metadata.directory) {
  3019. // calcolo lockServerUrl
  3020. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3021. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  3022. if (directory.lock)
  3023. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  3024. else
  3025. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  3026. }
  3027. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", _metadata.fileID]];
  3028. /******************************************* AHKActionSheet *******************************************/
  3029. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.view title:nil];
  3030. actionSheet.animationDuration = 0.2;
  3031. actionSheet.blurRadius = 0.0f;
  3032. actionSheet.blurTintColor = [UIColor colorWithWhite:0.0f alpha:0.50f];
  3033. actionSheet.buttonHeight = 50.0;
  3034. actionSheet.cancelButtonHeight = 50.0f;
  3035. actionSheet.separatorHeight = 5.0f;
  3036. actionSheet.automaticallyTintButtonImages = @(NO);
  3037. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].cryptocloud };
  3038. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  3039. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].brand };
  3040. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  3041. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  3042. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  3043. /******************************************* DIRECTORY *******************************************/
  3044. if (_metadata.directory) {
  3045. BOOL lockDirectory = NO;
  3046. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3047. // Directory bloccata ?
  3048. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", dirServerUrl]];
  3049. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  3050. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  3051. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  3052. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3053. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:_metadata.iconName] color:[NCBrandColor sharedInstance].brand]
  3054. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3055. height: 50.0
  3056. type: AHKActionSheetButtonTypeDisabled
  3057. handler: nil
  3058. ];
  3059. if (!lockDirectory && !_metadata.cryptated) {
  3060. [actionSheet addButtonWithTitle:titleFavorite
  3061. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetFavorite"] color:[NCBrandColor sharedInstance].brand]
  3062. backgroundColor:[UIColor whiteColor]
  3063. height: 50.0
  3064. type:AHKActionSheetButtonTypeDefault
  3065. handler:^(AHKActionSheet *as) {
  3066. // close swipe
  3067. [self setEditing:NO animated:YES];
  3068. if (_metadata.favorite)
  3069. [self removeFavorite:_metadata];
  3070. else
  3071. [self addFavorite:_metadata];
  3072. }];
  3073. }
  3074. if (_metadata.cryptated == NO && !lockDirectory) {
  3075. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3076. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  3077. backgroundColor:[UIColor whiteColor]
  3078. height: 50.0
  3079. type:AHKActionSheetButtonTypeDefault
  3080. handler:^(AHKActionSheet *as) {
  3081. // close swipe
  3082. [self setEditing:NO animated:YES];
  3083. [self openWindowShare:_metadata];
  3084. }];
  3085. }
  3086. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory) {
  3087. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3088. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3089. backgroundColor:[UIColor whiteColor]
  3090. height: 50.0
  3091. type:AHKActionSheetButtonTypeDefault
  3092. handler:^(AHKActionSheet *as) {
  3093. // close swipe
  3094. [self setEditing:NO animated:YES];
  3095. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  3096. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  3097. textField.placeholder = _metadata.fileNamePrint;
  3098. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  3099. }];
  3100. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3101. NSLog(@"Cancel action");
  3102. }];
  3103. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  3104. UITextField *fileName = alertController.textFields.firstObject;
  3105. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  3106. }];
  3107. okAction.enabled = NO;
  3108. [alertController addAction:cancelAction];
  3109. [alertController addAction:okAction];
  3110. [self presentViewController:alertController animated:YES completion:nil];
  3111. }];
  3112. }
  3113. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory) {
  3114. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3115. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3116. backgroundColor:[UIColor whiteColor]
  3117. height: 50.0
  3118. type:AHKActionSheetButtonTypeDefault
  3119. handler:^(AHKActionSheet *as) {
  3120. // close swipe
  3121. [self setEditing:NO animated:YES];
  3122. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3123. }];
  3124. }
  3125. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && _metadata.cryptated == NO) {
  3126. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  3127. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderphotocamera"] color:[NCBrandColor sharedInstance].brand]
  3128. backgroundColor:[UIColor whiteColor]
  3129. height: 50.0
  3130. type:AHKActionSheetButtonTypeDefault
  3131. handler:^(AHKActionSheet *as) {
  3132. // close swipe
  3133. [self setEditing:NO animated:YES];
  3134. // Settings new folder Automatatic upload
  3135. NSString *oldAutoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  3136. [[NCManageDatabase sharedInstance] setAccountAutoUploadFileName:_metadata.fileName];
  3137. [[NCManageDatabase sharedInstance] setAccountAutoUploadDirectory:serverUrl activeUrl:app.activeUrl];
  3138. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:oldAutoUploadDirectory directoryID:nil];
  3139. if (app.activeAccount.length > 0 && app.activePhotos)
  3140. [app.activePhotos reloadDatasourceForced];
  3141. [self readFolderWithForced:YES serverUrl:serverUrl];
  3142. NSLog(@"[LOG] Update Folder Photo");
  3143. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  3144. if ([autoUploadPath length] > 0)
  3145. [[CCSynchronize sharedSynchronize] readFolderServerUrl:autoUploadPath selector:selectorReadFolder];
  3146. }];
  3147. }
  3148. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES)) {
  3149. [actionSheet addButtonWithTitle:titoloLock
  3150. image:[UIImage imageNamed:@"actionSheetLock"]
  3151. backgroundColor:[UIColor whiteColor]
  3152. height: 50.0
  3153. type:AHKActionSheetButtonTypeEncrypted
  3154. handler:^(AHKActionSheet *as) {
  3155. // close swipe
  3156. [self setEditing:NO animated:YES];
  3157. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  3158. }];
  3159. }
  3160. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory && app.isCryptoCloudMode) {
  3161. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3162. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3163. backgroundColor:[UIColor whiteColor]
  3164. height: 50.0
  3165. type:AHKActionSheetButtonTypeEncrypted
  3166. handler:^(AHKActionSheet *as) {
  3167. // close swipe
  3168. [self setEditing:NO animated:YES];
  3169. [self performSelector:@selector(encyptedDecryptedFolder) withObject:nil];
  3170. }];
  3171. }
  3172. [actionSheet show];
  3173. }
  3174. /******************************************* FILE *******************************************/
  3175. if ([_metadata.type isEqualToString: k_metadataType_file] && !_metadata.directory) {
  3176. UIImage *iconHeader;
  3177. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3178. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]])
  3179. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]];
  3180. else
  3181. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3182. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3183. image: iconHeader
  3184. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3185. height: 50.0
  3186. type: AHKActionSheetButtonTypeDisabled
  3187. handler: nil
  3188. ];
  3189. if (!_metadata.cryptated) {
  3190. [actionSheet addButtonWithTitle:titleFavorite
  3191. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetFavorite"] color:[NCBrandColor sharedInstance].brand]
  3192. backgroundColor:[UIColor whiteColor]
  3193. height: 50.0
  3194. type:AHKActionSheetButtonTypeDefault
  3195. handler:^(AHKActionSheet *as) {
  3196. // close swipe
  3197. [self setEditing:NO animated:YES];
  3198. if (_metadata.favorite)
  3199. [self removeFavorite:_metadata];
  3200. else
  3201. [self addFavorite:_metadata];
  3202. }];
  3203. }
  3204. if (_metadata.cryptated == NO) {
  3205. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3206. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  3207. backgroundColor:[UIColor whiteColor]
  3208. height: 50.0
  3209. type:AHKActionSheetButtonTypeDefault
  3210. handler:^(AHKActionSheet *as) {
  3211. // close swipe
  3212. [self setEditing:NO animated:YES];
  3213. [self openWindowShare:_metadata];
  3214. }];
  3215. }
  3216. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  3217. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetOpenIn"] color:[NCBrandColor sharedInstance].brand]
  3218. backgroundColor:[UIColor whiteColor]
  3219. height: 50.0
  3220. type:AHKActionSheetButtonTypeDefault
  3221. handler:^(AHKActionSheet *as) {
  3222. // close swipe
  3223. [self setEditing:NO animated:YES];
  3224. [self performSelector:@selector(openIn:) withObject:_metadata];
  3225. }];
  3226. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3227. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3228. backgroundColor:[UIColor whiteColor]
  3229. height: 50.0
  3230. type:AHKActionSheetButtonTypeDefault
  3231. handler:^(AHKActionSheet *as) {
  3232. // close swipe
  3233. [self setEditing:NO animated:YES];
  3234. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  3235. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  3236. textField.placeholder = _metadata.fileNamePrint;
  3237. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  3238. }];
  3239. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3240. NSLog(@"Cancel action");
  3241. }];
  3242. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  3243. UITextField *fileName = alertController.textFields.firstObject;
  3244. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  3245. }];
  3246. okAction.enabled = NO;
  3247. [alertController addAction:cancelAction];
  3248. [alertController addAction:okAction];
  3249. [self presentViewController:alertController animated:YES completion:nil];
  3250. }];
  3251. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3252. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3253. backgroundColor:[UIColor whiteColor]
  3254. height: 50.0
  3255. type:AHKActionSheetButtonTypeDefault
  3256. handler:^(AHKActionSheet *as) {
  3257. // close swipe
  3258. [self setEditing:NO animated:YES];
  3259. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3260. }];
  3261. if (localFile || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3262. [actionSheet addButtonWithTitle:NSLocalizedString(@"_remove_local_file_", nil)
  3263. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRemoveLocal"] color:[NCBrandColor sharedInstance].brand]
  3264. backgroundColor:[UIColor whiteColor]
  3265. height: 50.0
  3266. type:AHKActionSheetButtonTypeDefault
  3267. handler:^(AHKActionSheet *as) {
  3268. // close swipe
  3269. [self setEditing:NO animated:YES];
  3270. [self performSelector:@selector(removeLocalFile:) withObject:_metadata];
  3271. }];
  3272. }
  3273. if (app.isCryptoCloudMode) {
  3274. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3275. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3276. backgroundColor:[UIColor whiteColor]
  3277. height: 50.0
  3278. type:AHKActionSheetButtonTypeEncrypted
  3279. handler:^(AHKActionSheet *as) {
  3280. // close swipe
  3281. [self setEditing:NO animated:YES];
  3282. [self performSelector:@selector(cmdEncryptedDecryptedFile) withObject:nil];
  3283. }];
  3284. }
  3285. [actionSheet show];
  3286. }
  3287. /******************************************* TEMPLATE *******************************************/
  3288. if ([_metadata.type isEqualToString: k_metadataType_template]) {
  3289. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3290. image: [UIImage imageNamed:_metadata.iconName]
  3291. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3292. height: 50.0
  3293. type: AHKActionSheetButtonTypeDisabled
  3294. handler: nil
  3295. ];
  3296. if ([_metadata.model isEqualToString:@"note"]) {
  3297. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3298. image:[UIImage imageNamed:@"actionSheetRename"]
  3299. backgroundColor:[UIColor whiteColor]
  3300. height: 50.0
  3301. type:AHKActionSheetButtonTypeDefault
  3302. handler:^(AHKActionSheet *as) {
  3303. // close swipe
  3304. [self setEditing:NO animated:YES];
  3305. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  3306. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  3307. textField.placeholder = _metadata.fileNamePrint;
  3308. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  3309. }];
  3310. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3311. NSLog(@"Cancel action");
  3312. }];
  3313. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  3314. UITextField *fileName = alertController.textFields.firstObject;
  3315. [self performSelectorOnMainThread:@selector(renameNote:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  3316. }];
  3317. okAction.enabled = NO;
  3318. [alertController addAction:cancelAction];
  3319. [alertController addAction:okAction];
  3320. [self presentViewController:alertController animated:YES completion:nil];
  3321. }];
  3322. }
  3323. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3324. image:[UIImage imageNamed:@"actionSheetMove"]
  3325. backgroundColor:[UIColor whiteColor]
  3326. height: 50.0
  3327. type:AHKActionSheetButtonTypeDefault
  3328. handler:^(AHKActionSheet *as) {
  3329. // close swipe
  3330. [self setEditing:NO animated:YES];
  3331. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3332. }];
  3333. [actionSheet show];
  3334. }
  3335. }
  3336. - (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
  3337. {
  3338. return NSLocalizedString(@"_delete_", nil);
  3339. }
  3340. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3341. {
  3342. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3343. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3344. return NO;
  3345. if (metadata == nil || metadata.errorPasscode || (metadata.cryptated && [metadata.title length] == 0) || metadata.sessionTaskIdentifier >= 0 || metadata.sessionTaskIdentifier >= 0) return NO;
  3346. else return YES;
  3347. }
  3348. - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
  3349. {
  3350. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3351. if (_metadata.errorPasscode || (_metadata.cryptated && [_metadata.title length] == 0) || _metadata.sessionTaskIdentifier >= 0 || _metadata.sessionTaskIdentifier >= 0) return UITableViewCellEditingStyleNone;
  3352. else return UITableViewCellEditingStyleDelete;
  3353. }
  3354. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  3355. {
  3356. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3357. BOOL lockDirectory = NO;
  3358. // Directory locked ?
  3359. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID] addFileName:_metadata.fileNameData];
  3360. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  3361. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil)
  3362. lockDirectory = YES;
  3363. if (lockDirectory && editingStyle == UITableViewCellEditingStyleDelete) {
  3364. [app messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  3365. return;
  3366. }
  3367. if (editingStyle == UITableViewCellEditingStyleDelete) {
  3368. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  3369. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  3370. style:UIAlertActionStyleDestructive
  3371. handler:^(UIAlertAction *action) {
  3372. [self performSelector:@selector(deleteFile) withObject:nil];
  3373. }]];
  3374. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  3375. style:UIAlertActionStyleCancel
  3376. handler:^(UIAlertAction *action) {
  3377. [alertController dismissViewControllerAnimated:YES completion:nil];
  3378. }]];
  3379. alertController.popoverPresentationController.sourceView = self.view;
  3380. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  3381. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3382. [alertController.view layoutIfNeeded];
  3383. [self presentViewController:alertController animated:YES completion:nil];
  3384. }
  3385. }
  3386. #pragma --------------------------------------------------------------------------------------------
  3387. #pragma mark - ==== Datasource ====
  3388. #pragma --------------------------------------------------------------------------------------------
  3389. - (void)clearDateReadDataSource:(NSNotification *)notification
  3390. {
  3391. _dateReadDataSource = Nil;
  3392. [self reloadDatasource];
  3393. }
  3394. - (void)reloadDatasource
  3395. {
  3396. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  3397. }
  3398. - (void)reloadDatasource:(NSString *)serverUrl fileID:(NSString *)fileID selector:(NSString *)selector
  3399. {
  3400. // test
  3401. if (app.activeAccount.length == 0 || serverUrl.length == 0)
  3402. return;
  3403. // Search Mode
  3404. if(_isSearchMode) {
  3405. if ([selector length] == 0 || [selector isEqualToString:selectorSearch]) {
  3406. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3407. } else {
  3408. [self readFolderWithForced:NO serverUrl:serverUrl];
  3409. }
  3410. [self tableViewReload];
  3411. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  3412. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  3413. _noFilesSearchDescription = @"";
  3414. }
  3415. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  3416. _noFilesSearchTitle = @"";
  3417. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  3418. }
  3419. [self.tableView reloadEmptyDataSet];
  3420. return;
  3421. }
  3422. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3423. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3424. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  3425. [app.activeTransfers reloadDatasource];
  3426. } else {
  3427. CCMain *main = [app.listMainVC objectForKey:serverUrl];
  3428. if (main) {
  3429. [main reloadDatasource];
  3430. } else {
  3431. [self tableViewReload];
  3432. [app.activeTransfers reloadDatasource];
  3433. }
  3434. }
  3435. return;
  3436. }
  3437. [app.activeTransfers reloadDatasource];
  3438. // Settaggio variabili per le ottimizzazioni
  3439. _directoryGroupBy = [CCUtility getGroupBySettings];
  3440. _directoryOrder = [CCUtility getOrderSettings];
  3441. // Controllo data lettura Data Source
  3442. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl == %@", serverUrl]];
  3443. NSDate *dateDateRecordDirectory = directory.dateReadDirectory;
  3444. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3445. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3446. _dateReadDataSource = [NSDate date];
  3447. // Data Source
  3448. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@", app.activeAccount, [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl]] sorted:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings]];
  3449. _sectionDataSource = [CCSectionDataSourceMetadata new];
  3450. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3451. } else {
  3452. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3453. }
  3454. [self tableViewReload];
  3455. }
  3456. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3457. {
  3458. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3459. if (selectedRows.count > 0) {
  3460. for (NSIndexPath *selectionIndex in selectedRows) {
  3461. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3462. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3463. [metadatas addObject:metadata];
  3464. }
  3465. }
  3466. return metadatas;
  3467. }
  3468. - (tableMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3469. {
  3470. NSInteger section = indexPath.section + 1;
  3471. NSInteger row = indexPath.row + 1;
  3472. NSInteger totSections =[_sectionDataSource.sections count] ;
  3473. if ((totSections < section) || (section > totSections)) {
  3474. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3475. return nil;
  3476. }
  3477. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3478. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3479. if (fileIDs) {
  3480. NSInteger totRows =[fileIDs count] ;
  3481. if ((totRows < row) || (row > totRows)) {
  3482. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3483. return nil;
  3484. }
  3485. } else {
  3486. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3487. return nil;
  3488. }
  3489. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3490. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3491. return metadata;
  3492. }
  3493. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3494. {
  3495. NSInteger totSections =[_sectionDataSource.sections count] ;
  3496. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3497. #if DEBUG
  3498. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:[NSString stringWithFormat:@"DEBUG [3] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section] delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3499. [alertView show];
  3500. #endif
  3501. return nil;
  3502. }
  3503. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3504. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3505. }
  3506. #pragma --------------------------------------------------------------------------------------------
  3507. #pragma mark - ==== Table ====
  3508. #pragma --------------------------------------------------------------------------------------------
  3509. - (void)tableViewSelect:(BOOL)edit
  3510. {
  3511. // chiudiamo eventuali swipe aperti
  3512. if (edit) [self.tableView setEditing:NO animated:NO];
  3513. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3514. [self.tableView setEditing:edit animated:YES];
  3515. _isSelectedMode = edit;
  3516. if (edit)
  3517. [self setUINavigationBarSelected];
  3518. else
  3519. [self setUINavigationBarDefault];
  3520. [self setTitle];
  3521. }
  3522. - (void)tableViewReload
  3523. {
  3524. // ricordiamoci le row selezionate
  3525. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3526. [self.tableView reloadData];
  3527. for (NSIndexPath *path in indexPaths)
  3528. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3529. [self setTableViewFooter];
  3530. if (self.tableView.editing)
  3531. [self setTitle];
  3532. }
  3533. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3534. {
  3535. return 60;
  3536. }
  3537. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3538. {
  3539. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3540. }
  3541. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3542. {
  3543. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3544. }
  3545. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3546. {
  3547. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3548. NSString *sectionTitle = [sections objectAtIndex:section];
  3549. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3550. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3551. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3552. return 20.f;
  3553. }
  3554. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3555. {
  3556. float shift;
  3557. UIVisualEffectView *visualEffectView;
  3558. // Titolo
  3559. NSString *titleSection;
  3560. // Controllo
  3561. if ([_sectionDataSource.sections count] == 0)
  3562. return nil;
  3563. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]]) titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3564. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]]) titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3565. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3566. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3567. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3568. else titleSection = NSLocalizedString(titleSection,nil);
  3569. // Formato titolo
  3570. NSString *currentDevice = [CCUtility currentDevice];
  3571. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3572. visualEffectView = [[UIVisualEffectView alloc] init];
  3573. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3574. } else {
  3575. UIVisualEffect *blurEffect;
  3576. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3577. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3578. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3579. }
  3580. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3581. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) shift = - 35;
  3582. else shift = - 20;
  3583. } else shift = - 10;
  3584. // Title
  3585. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3586. titleLabel.backgroundColor = [UIColor clearColor];
  3587. titleLabel.textColor = [UIColor blackColor];
  3588. titleLabel.font = [UIFont systemFontOfSize:12];
  3589. titleLabel.textAlignment = NSTextAlignmentLeft;
  3590. titleLabel.text = titleSection;
  3591. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3592. [visualEffectView addSubview:titleLabel];
  3593. // Elements
  3594. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3595. elementLabel.backgroundColor = [UIColor clearColor];
  3596. elementLabel.textColor = [UIColor blackColor];;
  3597. elementLabel.font = [UIFont systemFontOfSize:12];
  3598. elementLabel.textAlignment = NSTextAlignmentRight;
  3599. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3600. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3601. NSUInteger rowsCount = [metadatas count];
  3602. if (rowsCount == 0) return nil;
  3603. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3604. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3605. [visualEffectView addSubview:elementLabel];
  3606. return visualEffectView;
  3607. }
  3608. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3609. {
  3610. return [_sectionDataSource.sections indexOfObject:title];
  3611. }
  3612. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3613. {
  3614. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3615. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3616. else
  3617. return nil;
  3618. }
  3619. /*
  3620. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3621. {
  3622. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3623. }
  3624. }
  3625. */
  3626. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3627. {
  3628. NSString *typeCell;
  3629. NSString *dataFile;
  3630. NSString *lunghezzaFile;
  3631. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3632. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata]) {
  3633. return [tableView dequeueReusableCellWithIdentifier:@"CellMainTransfer"];
  3634. }
  3635. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  3636. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3637. else typeCell = @"CellMainTransfer";
  3638. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3639. // separator
  3640. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3641. // change color selection
  3642. UIView *selectionColor = [[UIView alloc] init];
  3643. selectionColor.backgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  3644. cell.selectedBackgroundView = selectionColor;
  3645. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [UIColor whiteColor];
  3646. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = [NCBrandColor sharedInstance].transferBackground;
  3647. // ----------------------------------------------------------------------------------------------------------
  3648. // DEFAULT
  3649. // ----------------------------------------------------------------------------------------------------------
  3650. cell.file.image = nil;
  3651. cell.status.image = nil;
  3652. cell.favorite.image = nil;
  3653. cell.shared.image = nil;
  3654. cell.local.image = nil;
  3655. cell.labelTitle.enabled = YES;
  3656. cell.labelTitle.text = @"";
  3657. cell.labelInfoFile.enabled = YES;
  3658. cell.labelInfoFile.text = @"";
  3659. cell.progressView.progress = 0.0;
  3660. cell.progressView.hidden = YES;
  3661. cell.cancelTaskButton.hidden = YES;
  3662. cell.reloadTaskButton.hidden = YES;
  3663. cell.stopTaskButton.hidden = YES;
  3664. // Encrypted color
  3665. if (metadata.cryptated) {
  3666. cell.labelTitle.textColor = [NCBrandColor sharedInstance].cryptocloud;
  3667. } else {
  3668. cell.labelTitle.textColor = [UIColor blackColor];
  3669. }
  3670. // ----------------------------------------------------------------------------------------------------------
  3671. // File Name & Folder
  3672. // ----------------------------------------------------------------------------------------------------------
  3673. // nome del file
  3674. cell.labelTitle.text = metadata.fileNamePrint;
  3675. // è una directory
  3676. if (metadata.directory) {
  3677. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3678. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3679. lunghezzaFile = @" ";
  3680. // ----------------------------------------------------------------------------------------------------------
  3681. // Favorite Folder
  3682. // ----------------------------------------------------------------------------------------------------------
  3683. if (metadata.favorite) {
  3684. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3685. }
  3686. } else {
  3687. // File
  3688. dataFile = [CCUtility dateDiff:metadata.date];
  3689. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3690. // Plist ancora da scaricare
  3691. if (metadata.cryptated && [metadata.title length] == 0) {
  3692. dataFile = @" ";
  3693. lunghezzaFile = @" ";
  3694. }
  3695. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  3696. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3697. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3698. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3699. if ([metadata.type isEqualToString: k_metadataType_template] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO)
  3700. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", dataFile];
  3701. if ([metadata.type isEqualToString: k_metadataType_file] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO) {
  3702. if (localFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]])
  3703. cell.local.image = [UIImage imageNamed:@"local"];
  3704. else
  3705. cell.local.image = nil;
  3706. //cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ • %@", dataFile, lunghezzaFile];
  3707. //cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ ◦ %@", dataFile, lunghezzaFile];
  3708. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ %@", dataFile, lunghezzaFile];
  3709. }
  3710. // Plist ancora da scaricare
  3711. if ([dataFile isEqualToString:@" "] && [lunghezzaFile isEqualToString:@" "])
  3712. cell.labelInfoFile.text = NSLocalizedString(@"_no_plist_pull_down_",nil);
  3713. cell.accessoryType = UITableViewCellAccessoryNone;
  3714. }
  3715. // ----------------------------------------------------------------------------------------------------------
  3716. // File Image View
  3717. // ----------------------------------------------------------------------------------------------------------
  3718. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3719. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  3720. cell.file.image = [app.icoImagesCache objectForKey:metadata.fileID];
  3721. if (cell.file.image == nil) {
  3722. NSString *fileID = metadata.fileID;
  3723. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  3724. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, fileID]];
  3725. [app.icoImagesCache setObject:image forKey:fileID];
  3726. dispatch_async(dispatch_get_main_queue(), ^{
  3727. CCCellMainTransfer *cell = [tableView cellForRowAtIndexPath:indexPath];
  3728. if (cell)
  3729. cell.file.image = image;
  3730. });
  3731. });
  3732. }
  3733. } else {
  3734. if (metadata.directory)
  3735. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:metadata.iconName] color:[NCBrandColor sharedInstance].brand];
  3736. else
  3737. cell.file.image = [UIImage imageNamed:metadata.iconName];
  3738. if (metadata.thumbnailExists)
  3739. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  3740. }
  3741. // ----------------------------------------------------------------------------------------------------------
  3742. // Image Status cyptated & Lock Passcode
  3743. // ----------------------------------------------------------------------------------------------------------
  3744. // File Cyptated
  3745. if (metadata.cryptated && metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_template] == NO) {
  3746. cell.status.image = [UIImage imageNamed:@"lock"];
  3747. }
  3748. // Directory con passcode lock attivato
  3749. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileNameData];
  3750. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  3751. if (metadata.directory && (directory.lock && [[CCUtility getBlockCode] length]))
  3752. cell.status.image = [UIImage imageNamed:@"passcode"];
  3753. // ----------------------------------------------------------------------------------------------------------
  3754. // Favorite
  3755. // ----------------------------------------------------------------------------------------------------------
  3756. if (metadata.favorite) {
  3757. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3758. }
  3759. // ----------------------------------------------------------------------------------------------------------
  3760. // Share
  3761. // ----------------------------------------------------------------------------------------------------------
  3762. NSString *shareLink = [app.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3763. NSString *shareUserAndGroup = [app.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3764. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3765. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3766. // Aggiungiamo il Tap per le shared
  3767. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3768. if (isShare) {
  3769. if (metadata.directory) {
  3770. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3771. cell.shared.userInteractionEnabled = NO;
  3772. } else {
  3773. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3774. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3775. [tap setNumberOfTapsRequired:1];
  3776. cell.shared.userInteractionEnabled = YES;
  3777. [cell.shared addGestureRecognizer:tap];
  3778. }
  3779. }
  3780. if (isMounted) {
  3781. if (metadata.directory) {
  3782. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_external"] color:[NCBrandColor sharedInstance].brand];
  3783. cell.shared.userInteractionEnabled = NO;
  3784. } else {
  3785. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareMounted"] color:[NCBrandColor sharedInstance].brand];
  3786. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3787. [tap setNumberOfTapsRequired:1];
  3788. cell.shared.userInteractionEnabled = YES;
  3789. [cell.shared addGestureRecognizer:tap];
  3790. }
  3791. }
  3792. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3793. if (metadata.directory) {
  3794. if ([shareLink length] > 0)
  3795. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_public"] color:[NCBrandColor sharedInstance].brand];
  3796. if ([shareUserAndGroup length] > 0)
  3797. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3798. cell.shared.userInteractionEnabled = NO;
  3799. } else {
  3800. if ([shareLink length] > 0)
  3801. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareLink"] color:[NCBrandColor sharedInstance].brand];
  3802. if ([shareUserAndGroup length] > 0)
  3803. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3804. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3805. [tap setNumberOfTapsRequired:1];
  3806. cell.shared.userInteractionEnabled = YES;
  3807. [cell.shared addGestureRecognizer:tap];
  3808. }
  3809. }
  3810. } else {
  3811. cell.shared.userInteractionEnabled = NO;
  3812. }
  3813. // ----------------------------------------------------------------------------------------------------------
  3814. // downloadFile
  3815. // ----------------------------------------------------------------------------------------------------------
  3816. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  3817. if (metadata.cryptated) cell.status.image = [UIImage imageNamed:@"statusdownloadcrypto"];
  3818. else cell.status.image = [UIImage imageNamed:@"statusdownload"];
  3819. // sessionTaskIdentifier : RELOAD + STOP
  3820. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) {
  3821. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptaskcrypto"] forState:UIControlStateNormal];
  3822. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3823. cell.cancelTaskButton.hidden = NO;
  3824. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3825. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3826. cell.reloadTaskButton.hidden = NO;
  3827. }
  3828. // sessionTaskIdentifierPlist : RELOAD
  3829. if (metadata.sessionTaskIdentifierPlist != k_taskIdentifierDone) {
  3830. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3831. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3832. cell.reloadTaskButton.hidden = NO;
  3833. }
  3834. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3835. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3836. if (progress > 0) {
  3837. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3838. else cell.progressView.progressTintColor = [UIColor blackColor];
  3839. cell.progressView.progress = progress;
  3840. cell.progressView.hidden = NO;
  3841. }
  3842. // ----------------------------------------------------------------------------------------------------------
  3843. // downloadFile Error
  3844. // ----------------------------------------------------------------------------------------------------------
  3845. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3846. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3847. if ([metadata.sessionError length] == 0)
  3848. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3849. else
  3850. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3851. }
  3852. }
  3853. // ----------------------------------------------------------------------------------------------------------
  3854. // uploadFile
  3855. // ----------------------------------------------------------------------------------------------------------
  3856. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3857. if (metadata.cryptated) cell.status.image = [UIImage imageNamed:@"statusuploadcrypto"];
  3858. else cell.status.image = [UIImage imageNamed:@"statusupload"];
  3859. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetaskcrypto"] forState:UIControlStateNormal];
  3860. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetask"] forState:UIControlStateNormal];
  3861. cell.cancelTaskButton.hidden = NO;
  3862. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3863. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3864. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3865. if (metadata.cryptated) cell.status.image = [UIImage imageNamed:@"statusstopcrypto"];
  3866. else cell.status.image = [UIImage imageNamed:@"statusstop"];
  3867. cell.reloadTaskButton.hidden = NO;
  3868. cell.stopTaskButton.hidden = YES;
  3869. } else {
  3870. if (metadata.cryptated)[cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptaskcrypto"] forState:UIControlStateNormal];
  3871. else [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3872. cell.stopTaskButton.hidden = NO;
  3873. cell.reloadTaskButton.hidden = YES;
  3874. }
  3875. // se non c'è una preview in bianconero metti l'immagine di default
  3876. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]] == NO)
  3877. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"uploaddisable"] color:[NCBrandColor sharedInstance].brand];
  3878. cell.labelTitle.enabled = NO;
  3879. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3880. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3881. if (progress > 0) {
  3882. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3883. else cell.progressView.progressTintColor = [UIColor blackColor];
  3884. cell.progressView.progress = progress;
  3885. cell.progressView.hidden = NO;
  3886. }
  3887. // ----------------------------------------------------------------------------------------------------------
  3888. // uploadFileError
  3889. // ----------------------------------------------------------------------------------------------------------
  3890. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3891. cell.labelTitle.enabled = NO;
  3892. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3893. if ([metadata.sessionError length] == 0)
  3894. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3895. else
  3896. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3897. }
  3898. }
  3899. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3900. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3901. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3902. return cell;
  3903. }
  3904. - (void)setTableViewFooter
  3905. {
  3906. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3907. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3908. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3909. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3910. UIFont *appFont = [UIFont systemFontOfSize:12];
  3911. footerLabel.font = appFont;
  3912. footerLabel.textColor = [UIColor grayColor];
  3913. footerLabel.backgroundColor = [UIColor clearColor];
  3914. footerLabel.textAlignment = NSTextAlignmentCenter;
  3915. NSString *folders;
  3916. NSString *files;
  3917. NSString *footerText;
  3918. if (_sectionDataSource.directories > 1) {
  3919. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3920. } else if (_sectionDataSource.directories == 1){
  3921. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3922. } else {
  3923. folders = @"";
  3924. }
  3925. if (_sectionDataSource.files > 1) {
  3926. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3927. } else if (_sectionDataSource.files == 1){
  3928. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3929. } else {
  3930. files = @"";
  3931. }
  3932. if ([folders isEqualToString:@""]) {
  3933. footerText = files;
  3934. } else if ([files isEqualToString:@""]) {
  3935. footerText = folders;
  3936. } else {
  3937. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3938. }
  3939. footerLabel.text = footerText;
  3940. [footerView addSubview:footerLabel];
  3941. [self.tableView setTableFooterView:footerView];
  3942. }
  3943. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3944. {
  3945. NSString *textMessage;
  3946. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  3947. // settiamo il record file.
  3948. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3949. // se non può essere selezionata deseleziona
  3950. if ([cell isEditing] == NO)
  3951. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3952. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3953. if (self.tableView.editing) {
  3954. [self setTitle];
  3955. return;
  3956. }
  3957. // test crash
  3958. NSArray *metadatas = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  3959. if (indexPath.row >= [metadatas count]) return;
  3960. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3961. // se è in corso una sessione
  3962. if ([_metadata.session length] > 0) return;
  3963. if (_metadata.errorPasscode) {
  3964. // se UUID è nil lo sta ancora caricando quindi esci
  3965. if (!_metadata.uuid) return;
  3966. // esiste un hint ??
  3967. NSString *hint = [[CCCrypto sharedManager] getHintFromFile:_metadata.fileName isLocal:NO directoryUser:app.directoryUser];
  3968. // qui !! la richiesta della nuova passcode
  3969. if ([_metadata.uuid isEqualToString:[CCUtility getUUID]]) {
  3970. // stesso UUID ... la password è stata modificata !!!!!!
  3971. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_same_device_different_passcode_hint_",nil), hint];
  3972. else textMessage = NSLocalizedString(@"_same_device_different_passcode_", nil);
  3973. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3974. [alertView show];
  3975. } else {
  3976. // UUID diverso.
  3977. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_hint_",nil), _metadata.nameCurrentDevice, hint];
  3978. else textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_",nil), _metadata.nameCurrentDevice];
  3979. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3980. [alertView show];
  3981. }
  3982. // chiediamo la passcode e ricarichiamo tutto.
  3983. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3984. viewController.delegate = self;
  3985. viewController.fromType = CCBKPasscodeFromPasscode;
  3986. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3987. viewController.passcodeInputView.maximumLength = 64;
  3988. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3989. viewController.inputViewTitlePassword = NO;
  3990. viewController.title = [NCBrandOptions sharedInstance].brand;
  3991. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3992. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  3993. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3994. [self presentViewController:navigationController animated:YES completion:nil];
  3995. }
  3996. // modello o plist con il title a 0 allora è andato storto qualcosa ... ricaricalo
  3997. if (_metadata.cryptated && [_metadata.title length] == 0) {
  3998. NSString* selector;
  3999. if ([_metadata.type isEqualToString: k_metadataType_template]) selector = selectorLoadModelView;
  4000. else selector = selectorLoadPlist;
  4001. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:NO downloadPlist:YES selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  4002. return;
  4003. }
  4004. // se il plist è caricato ed è un modello aprilo
  4005. if ([_metadata.type isEqualToString:k_metadataType_template]) [self openModel:_metadata.model isNew:false];
  4006. // file
  4007. if (_metadata.directory == NO && _metadata.errorPasscode == NO && [_metadata.type isEqualToString: k_metadataType_file]) {
  4008. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  4009. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  4010. [self downloadFileSuccess:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil];
  4011. } else {
  4012. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadFileView selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  4013. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  4014. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  4015. }
  4016. }
  4017. if (_metadata.directory) [self performSegueDirectoryWithControlPasscode:true];
  4018. }
  4019. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  4020. {
  4021. [self setTitle];
  4022. }
  4023. #pragma --------------------------------------------------------------------------------------------
  4024. #pragma mark ===== Navigation ====
  4025. #pragma --------------------------------------------------------------------------------------------
  4026. - (BOOL)shouldPerformSegue
  4027. {
  4028. // if background return
  4029. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  4030. if (self.view.window == NO)
  4031. return NO;
  4032. // Collapsed ma siamo già in detail esci
  4033. if (self.splitViewController.isCollapsed)
  4034. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  4035. // Video in esecuzione esci
  4036. if (_detailViewController.photoBrowser.currentVideoPlayerViewController.isViewLoaded && _detailViewController.photoBrowser.currentVideoPlayerViewController.view.window) return NO;
  4037. return YES;
  4038. }
  4039. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  4040. {
  4041. id viewController = segue.destinationViewController;
  4042. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  4043. tableMetadata *metadata;
  4044. if ([viewController isKindOfClass:[UINavigationController class]]) {
  4045. UINavigationController *nav = viewController;
  4046. _detailViewController = (CCDetail *)nav.topViewController;
  4047. } else {
  4048. _detailViewController = segue.destinationViewController;
  4049. }
  4050. if ([sender isKindOfClass:[tableMetadata class]]) {
  4051. metadata = sender;
  4052. [allRecordsDataSourceImagesVideos addObject:sender];
  4053. } else {
  4054. metadata = _metadata;
  4055. for (NSString *fileID in _sectionDataSource.allEtag) {
  4056. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  4057. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  4058. [allRecordsDataSourceImagesVideos addObject:metadata];
  4059. }
  4060. }
  4061. _detailViewController.metadataDetail = metadata;
  4062. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  4063. _detailViewController.dateFilterQuery = nil;
  4064. [_detailViewController setTitle:metadata.fileNamePrint];
  4065. }
  4066. // can i go to next viewcontroller
  4067. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  4068. {
  4069. NSString *nomeDir;
  4070. if(self.tableView.editing == NO && _metadata.errorPasscode == NO){
  4071. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  4072. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  4073. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  4074. // SE siamo in presenza di una directory bloccata E è attivo il block E la sessione password Lock è senza data ALLORA chiediamo la password per procedere
  4075. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil && controlPasscode) {
  4076. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  4077. viewController.delegate = self;
  4078. viewController.fromType = CCBKPasscodeFromLockDirectory;
  4079. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  4080. viewController.inputViewTitlePassword = YES;
  4081. if ([CCUtility getSimplyBlockCode]) {
  4082. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  4083. viewController.passcodeInputView.maximumLength = 6;
  4084. } else {
  4085. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  4086. viewController.passcodeInputView.maximumLength = 64;
  4087. }
  4088. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  4089. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  4090. viewController.touchIDManager = touchIDManager;
  4091. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  4092. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  4093. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  4094. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  4095. [self presentViewController:navController animated:YES completion:nil];
  4096. return;
  4097. }
  4098. if (_metadata.cryptated) nomeDir = [_metadata.fileName substringToIndex:[_metadata.fileName length]-6];
  4099. else nomeDir = _metadata.fileName;
  4100. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  4101. CCMain *viewController = [app.listMainVC objectForKey:serverUrlPush];
  4102. if (viewController.isViewLoaded == false || viewController == nil) {
  4103. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMainVC"];
  4104. viewController.isFolderEncrypted = _metadata.cryptated;
  4105. viewController.serverUrl = serverUrlPush;
  4106. viewController.titleMain = _metadata.fileNamePrint;
  4107. viewController.textBackButton = _titleMain;
  4108. // save self
  4109. [app.listMainVC setObject:viewController forKey:serverUrlPush];
  4110. }
  4111. // OFF SearchBar
  4112. [viewController cancelSearchBar];
  4113. [self.navigationController pushViewController:viewController animated:YES];
  4114. }
  4115. }
  4116. @end