CCMain.m 247 KB

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