CCMain.m 222 KB

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