CCMain.m 238 KB

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