CCMain.m 238 KB

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