CCMain.m 237 KB

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