CCMain.m 230 KB

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