CCMain.m 225 KB

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