CCMain.m 238 KB

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