CCMain.m 239 KB

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